LightLogger 4.3.2

dotnet add package LightLogger --version 4.3.2
                    
NuGet\Install-Package LightLogger -Version 4.3.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LightLogger" Version="4.3.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LightLogger" Version="4.3.2" />
                    
Directory.Packages.props
<PackageReference Include="LightLogger" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LightLogger --version 4.3.2
                    
#r "nuget: LightLogger, 4.3.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LightLogger@4.3.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LightLogger&version=4.3.2
                    
Install as a Cake Addin
#tool nuget:?package=LightLogger&version=4.3.2
                    
Install as a Cake Tool

LightLogger

LightLogger is a lightweight logging library designed for simplicity and easy integration into .NET applications. It provides first-class support for dependency injection and allows developers to log messages either to the console or to a file with minimal configuration.

Features

  • Dependency injection–friendly (ILightLogger<T>)
  • Generic logger automatically captures the source type
  • Multiple logging modes: Console and SaveToFile
  • Minimal required configuration to get started
  • Optional file size–based log rotation
  • Configurable log message template
  • Configurable timestamp format
  • Colorized console output
  • Suitable for console, desktop, and service applications
  • Structured logging support (JSON)
  • Global properties
  • Integrated support of File header (signature)

What’s New in This Version

  • Environment Logging (File Signature)
    • LightLogger automatically writes environment information once per log file.
    • It provides clear context (machine, OS, app version, etc.) without duplication.
  • Exception Logging at All Levels – You can now log exceptions not only as errors but also with Information, Debug, and Warning levels.
    • Log exceptions with full stack traces
    • Exceptions are automatically included in structured JSON output
  • Scoped Logging (BeginScope)
    • Attach contextual properties to all log entries within a scope
    • Fully async-safe
    • Supports dictionaries, name/value pairs, and anonymous objects
    • Nested scopes are supported, with inner scopes overriding outer values

Installation

Add the LightLogger package to your project:

dotnet add package LightLogger

Basic Usage

1. Register services and configure the logger

Register the logger and its configuration with the dependency injection container:

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddOptions<LightLoggerConfiguration>();
services.Configure<LightLoggerConfiguration>(options =>
{
    options.LogDirectory = @"C:\Logs";
    options.LogFileName = "LightLogger.log";
    options.Mode = LoggingMode.SaveToFile;

    // Optional file rotation
    options.EnableFileRotation = true;
    options.MaxFileSizeBytes = 10 * FileSize.MB;    
});

// Register open-generic logger
services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));

var provider = services.BuildServiceProvider();

Note

LogDirectory and LogFileName are required only when SaveToFile mode is enabled.

Configure using appsettings.json

{
  "LightLogger": {
    "LogDirectory": "C:\\Logs",
    "LogFileName": "LightLogger.log",
    "Mode": "SaveToFile",
    "EnableFileRotation": true,
    "MaxFileSizeBytes": 10485760,
    "MessageTemplate": "[{Timestamp}] [{Level}] [{Source}] {Message}",
    "TimestampFormat": "yyyy-MM-dd HH:mm:ss"    
  }
}

Register configuration at startup

services
    .AddOptions<LightLoggerConfiguration>()
    .Bind(configuration.GetSection("LightLogger"));

services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));

By default, logs are written to the console only if no configuration is provided and the application is a console app. For other application types, leaving the logger unconfigured will result in no output. In such cases, using SaveToFile mode is the recommended approach.

2. Inject and log

public class MyService
{
    private readonly ILightLogger<MyService> _logger;

    public MyService(ILightLogger<MyService> logger)
    {
        _logger = logger;
    }

    public void MyMethod()
    {
        logger.LogInformation("Service started");
    }
}

Global Properties

LightLogger allows you to define global properties that are automatically included in every log entry. Global properties apply only to structured logging and are ignored in text logging. This is useful for including application-wide context, such as application name, environment, or version, without repeating it in every log call.

Key points:
  • Global properties are merged automatically with any properties provided in individual log calls.
  • Useful for context like application name, environment, or version.
  • Works in structured JSON logging mode.

Configuration Example

var services = new ServiceCollection();

// Configure LightLogger
services.AddOptions<LightLoggerConfiguration>()
    .Configure(options =>
    {
        options.Mode = LoggingMode.SaveToFile;
        // Directory where logs will be saved
        options.LogDirectory = @"C:\Logs";

        // Base filename for logs
        options.LogFileName = "app-log";

        // Choose between structured JSON logs or simple text logs
        options.LogFormat = LogFormat.Structured; // or LogFormat.Text


        // Global properties applied to all structured logs only.
        // Optional: include global properties for structured logs only
        options.GlobalProperties = new Dictionary<string, object>
        {
            { "ApplicationVersion", "1.2.0" },
            { "Environment", "Production" }
        };
         // Optional: configure maximum file size for rotation
        options.EnableFileRotation = true;
        options.MaxFileSizeBytes = 5_000_000; // 5 MB

        // Optional: customize timestamp format
        options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";

        // Optional: customize text message template (applies to text logging only)
        options.MessageTemplate = "[{Timestamp}] [{Level}] {Source}.{Member}: {Message}";
    });

// Register the open-generic logger
services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));

var provider = services.BuildServiceProvider();
var logger = provider.GetRequiredService<ILightLogger<Program>>();

Logging Example

// Log a simple message
logger.LogInformation("Application started");

// Log with additional properties (merged with global properties)
logger.LogInformation(
    "User logged in",
    new Dictionary<string, object> { { "UserId", 123 }, { "Role", "Admin" } });

Resulting Structured Log (JSON)

Simple log:
{
  "Timestamp": "2025-12-25 14:30:01",
  "Level": "Information",
  "Source": "Program",
  "Member": "Main",
  "Message": "Application started",
  "LogFormat": "Structured",
  "GlobalProperties": {
    "Application": "MyApp",
    "Environment": "Development",
    "Version": "1.2.0"
  }
}
Log with additional properties:
{
  "Timestamp": "2025-12-25 14:31:10",
  "Level": "Information",
  "Source": "Program",
  "Member": "Main",
  "Message": "User logged in",
  "GlobalProperties": {
    "Application": "MyApp",
    "Environment": "Development",
    "Version": "1.2.0",
    "UserId": 123,
    "Role": "Admin"
  }
}

Scoped Logging (BeginScope) 🆕

LightLogger supports logical logging scopes. Scopes allow you to attach contextual properties (e.g. RequestId, UserId, OperationName) to all log entries written within a block, without passing those properties to every log call.

Scopes are:

  • ✅ Async-safe
  • ✅ Automatically merged into structured JSON logs
  • ❌ Ignored in text logs (by design)

Basic Scope Example

using (_logger.BeginScope(new Dictionary<string, object>
{
    { "RequestId", "REQ-123" },
    { "UserId", 42 }
}))
{
    _logger.LogInformation("Processing request");
    _logger.LogWarning("Slow response detected");
}

Scope with Name / Value

using (_logger.BeginScope("OrderId", 9876))
{
    _logger.LogInformation("Order processing started");
}

Scope with Anonymous Object

using (_logger.BeginScope(new { CorrelationId = "abc-123", Region = "us-east" }))
{
    _logger.LogInformation("Calling downstream service");
}

Nested Scopes

using (_logger.BeginScope(new { RequestId = "REQ-1", UserId = 42 }))
{
    _logger.LogInformation("Request started");

    using (_logger.BeginScope(new { UserId = 99 }))
    {
        _logger.LogInformation("Impersonation active");
    }

    _logger.LogInformation("Request completed");
}
Resulting behavior

Outer logs include RequestId = REQ-1, UserId = 42

Inner logs include RequestId = REQ-1, UserId = 99

Important Notes
  • Scopes are only included in structured logs and are ignored in text logs
  • Scopes flow correctly across async/await
  • Disposing a scope automatically removes it.

Environment Logging 🆕

LightLogger supports automatic environment (file signature) logging that is:

  • ✅ Written once per log file
  • ✅ Rewritten only when file rotation occurs
  • ✅ Logged before any application logs
  • ✅ Available in both text and structured (JSON) logs
  • ✅ Fully configuration-driven

Environment logging is configured once via configuration (e.g. appsettings.json).

{
  "LightLogger": {
    "LogDirectory": "C:\\Logs",
    "LogFileName": "LightLogger.log",
    "Mode": "SaveToFile",
    "EnableFileRotation": true,
    "MaxFileSizeBytes": 10485760,
    "MessageTemplate": "[{Timestamp}] [{Level}] [{Source}] {Message}",
    "TimestampFormat": "yyyy-MM-dd HH:mm:ss" 
    "FileSignature": {
        "Application": "MyApp",
        "Database": "PostgreSQL",
        "Version": "1.0.0-beta"
      }
  }
}
Text Log result
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] ==================== ENVIRONMENT INFO ====================
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] MachineName : M24157836
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] OSVersion   : Microsoft Windows NT 10.0.26100.0
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] UserName    : Sophia
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] Application : MyApp
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] Database    : PostgreSQL
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] Version     : 1.0.0-beta
[2026-01-02 19:19:46] [Information] [EnvironmentLogger.LogEnvironment] ==================== ENVIRONMENT INFO ====================

Structured log result
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"==================== ENVIRONMENT INFO ====================","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"MachineName : M24157836","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"OSVersion : Microsoft Windows NT 10.0.26100.0","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"UserName : Sophia","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"Application : MyApp","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"Database : PostgreSQL","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"Version : 1.0.0-beta","Category":"Environment"}
{"Timestamp":"2026-01-03 16:20:35 41","Level":"Information","Source":"EnvironmentLogger","Member":"LogEnvironment","Message":"==================== ENVIRONMENT INFO ====================","Category":"Environment"}

Note: The MachineName, OSVersion, and UserName fields are logged automatically, even when not specified in configuration. These values are provided by built-in defaults to guarantee consistent environment metadata across all log files.

Logging Exceptions at different levels 🆕

LightLogger supports exception logging at all levels.

Property Description
Information _logger.LogInformation(ex, "Validation failed, using fallback configuration");
Debug _logger.Debug(ex, "Validation failed, using fallback configuration");
Warning _logger.Warning(ex, "Validation failed, using fallback configuration");
Error _logger.Error(ex, "Validation failed, using fallback configuration");

Exception logging with properties (structured context)

try
{
   SaveCustomer(customer);
}
catch (Exception ex)
{
   _logger.LogError( ex, "Error saving customer", new Dictionary<string, object>
      {
         ["CustomerId"] = customer.Id,
         ["Email"] = customer.Email,
         ["Operation"] = "SaveCustomer"
      });
}

Exception logging with scopes

using (_logger.BeginScope("RequestId", requestId))
using (_logger.BeginScope("UserId", userId))
{
   try
   {
      HandleRequest();
   }
   catch (Exception ex)
   {
      _logger.LogError(ex, "Unhandled exception while handling request");
   }
}

Key Configuration Options

Property Description
LogDirectory Path where log files will be stored. Required.
LogFileName Base name of log files. Required.
LogFormat Structured for JSON logs (.jsonl) or Text for plain text logs.
GlobalProperties Key-value pairs included automatically in structured logs only. Ignored in text logs.
EnableFileRotation Enables file rotation based on MaxFileSizeBytes.
MaxFileSizeBytes Maximum file size before creating a new log file (applies to both structured and text logs).
TimestampFormat Format for timestamps in logs (applies to both structured and text logs).
MessageTemplate Template for text logs only. Supports {Timestamp}, {Level}, {Source}, {Member}, {Message}.
Mode Type of logging output: Console (writes to console only) or SaveToFile (writes to disk).
FileSignature Creates a block of metadata written at the top of each log file.

Choosing Structured vs Text Logging

  • Structured Logging (LogFormat.Structured):

    • Writes JSONL files.
    • Supports global properties.
    • Best for automated log processing, analytics, and aggregation tools.
  • Text Logging (LogFormat.Text):

    • Writes plain text files.
    • Simple and human-readable.
    • Global properties are ignored.
    • Ideal for console output or simple file-based logs.

Message Formatting

LightLogger supports customizable log message templates, allowing you to control the structure and appearance of each log entry. Below are a few examples demonstrating how a message template can be customized:

[{Timestamp}] [{Level}] [{Source}] {Message}
[{Timestamp}] - [{Level}] - [{Source}] - {Message}
{Timestamp} - [{Level}] - {Source} - {Message}
[{Timestamp}] - [{Level}] - {Message}

You can freely adjust the ordering, separators, and included placeholders to match your logging standards or personal preference.

Supported placeholders

LightLogger recognizes the following placeholders in message templates:

Placeholder Description
{Timestamp} The date and time when the log entry was created. The format is controlled by the TimestampFormat configuration setting.
{Level} The log level (e.g., Debug, Information, Warning, Error)
{Source} The source of the log entry, typically the calling class and method name.
{Message} The actual log message content provided by the application.

If no template or timestamp format is provided, safe defaults are applied automatically.

Logging Modes

LightLogger supports two logging modes:

Mode Description
Console Writes logs to the console (console apps only)
SaveToFile Writes logs to disk

Files are named using the following pattern:

<LogFileName>-yyyy-MM-dd.log // For text logs
<LogFileName>-yyyy-MM-dd.jsonl // for structured logs

File rotation

When enabled ("EnableFileRotation": true,), LightLogger automatically creates a new log file once the current file exceeds the configured size

LightLogger-2025-12-19.log
LightLogger-2025-12-19-1.log
LightLogger-2025-12-19-2.log

LightLogger-2025-12-19.jsonl
LightLogger-2025-12-19-1.jsonl
LightLogger-2025-12-19-2.jsonl

Log files are rotated when they reach a configured size or when a new time period begins.

Resulting Files

Log Type Filename
Text app-2025-01-18.log
Structured app-2025-01-18.jsonl
Rotated app-2025-01-18-2.jsonl

WPF Application Example (using appsetting.json configuration)

public partial class App : Application
{
    public static IHost AppHost { get; private set; }

    protected override async void OnStartup(StartupEventArgs e)
    {
        AppHost = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services
                    .AddOptions<LightLoggerConfiguration>()
                    .Bind(context.Configuration.GetSection("LightLogger"));

                services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));
            })
            .Build();

        await AppHost.StartAsync();

        var logger = AppHost.Services.GetRequiredService<ILightLogger<App>>();
        logger.LogInformation("WPF application started");

        base.OnStartup(e);
        new MainWindow().Show();
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        var logger = AppHost.Services.GetRequiredService<ILightLogger<App>>();
        logger.LogInformation("WPF application shutting down");

        await AppHost.StopAsync();
        base.OnExit(e);
    }
}
Important

WPF applications do not have a console. Use SaveToFile mode for reliable logging.

Windows Service Example

public class Worker : BackgroundService
{
    private readonly ILightLogger<Worker> _logger;

    public Worker(ILightLogger<Worker> logger)
    {
        _logger = logger;
    }

      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
         try
         {
            _logger.LogInformation("Windows service started");

            while (!stoppingToken.IsCancellationRequested)
            {
               _logger.LogDebug("Service heartbeat");
               await Task.Delay(5000, stoppingToken);
            }

            _logger.LogInformation("Windows service stopping");
         }
         catch (Exception ex)
         {
            _logger.LogError(ex, "An error occured.");
         }
      }
}

Service registration

Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services
            .AddOptions<LightLoggerConfiguration>()
            .Bind(context.Configuration.GetSection("LightLogger"));

        services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));
        services.AddHostedService<Worker>();
    })
    .Build()
    .Run();

Example: Console Application (Configured using IOptions<>)

using LightLogger;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();

        services.AddOptions<LightLoggerConfiguration>()
            .Configure(options =>
            {
                options.Mode = LoggingMode.SaveToFile;
                options.LogDirectory = @"C:\temp";
                options.LogFileName = "MyLogFile.log";
                options.EnableFileRotation = true;
                options.MaxFileSizeBytes = 5 * FileSize.MB;
            });

        services.AddSingleton(typeof(ILightLogger<>), typeof(LightLogger<>));

        using var provider = services.BuildServiceProvider();

        var logger = provider.GetRequiredService<ILightLogger<Program>>();

        logger.LogError("Example of error logging");
        logger.LogWarning("Example of warning logging");
        logger.LogDebug("Example of debug logging");
        logger.LogInformation("Example of info logging");
    }
}

Example: Console Application (No Configuration Required)

using LightLogger;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();

        // Zero configuration required
        services.AddLightLogger();

        var provider = services.BuildServiceProvider();

        var logger = provider.GetRequiredService<ILightLogger<Program>>();

        logger.LogInformation("Application started");
        logger.LogWarning("Warning example");
        logger.LogError("Error example");
    }
}

Best Practices

  • Configure LightLogger once at application startup
  • Register the logger as a singleton
  • Inject ILightLogger<T> instead of resolving manually
  • Let defaults handle missing configuration
  • Keep logging configuration separate from business logic
  • Prefer file logging for WPF and Windows Services
  • Use structured logging for production telemetry systems
  • Use global properties for shared context

🛠 Troubleshooting

❌ Logs are not being written

  • Ensure Mode = SaveToFile
  • Verify directory permissions
  • Ensure appsettings.json is copied to output

❌ Global properties are missing from logs

  • Global properties only apply to structured logging
  • Ensure LogFormat = Structured

❌ Nothing logs in WPF or Windows Service

  • Console logging is not supported in non-console applications
  • Use SaveToFile mode instead

❌ Visual Studio Output window shows nothing

  • LightLogger does not log to Debug or Trace
  • This is intentional to keep the library simple and predictable
  • Use file logging for diagnostics
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.3.2 112 1/10/2026
4.2.6 101 12/30/2025
4.1.1 215 12/15/2025
4.1.0 446 12/15/2025
4.0.8 463 12/15/2025
1.0.2.2 839 5/23/2020
1.0.2.1 726 8/3/2019
1.0.2 728 8/2/2019
1.0.1 695 7/24/2019
1.0.0 726 7/23/2019