Friday, September 27, 2024

Different ways to configure logging and access Logger in ASP.NET Core



Objectives

  • To learn different ways to configure logging in .NET6 and later versions
    • Configure Logging in Program.cs using Host
    • Configure Logging via appsettings.json
    • Add Custom Logging Providers e.g. Serilog
    • Configure logging based on environments e.g. Development or Production
  • To access Logger in Application Code

In ASP.NET Core .NET 6 and later versions, the WebApplication class uses the Minimal Hosting Model, which provides a simplified way to configure logging. The logging configuration can be done in a few different ways depending on the requirements. Since the WebApplication class internally uses the Generic Host, logging can be configured via the Host property of WebApplicationBuilder or directly in appsettings.json. Here's how you can configure logging using the WebApplication class:

Configure Logging in Program.cs

You can configure logging via the Host property of the WebApplicationBuilder. This is typically done within the ConfigureLogging method, which allows you to clear default providers, add custom logging providers, and configure log levels.

Example: Configure Logging in Program.cs
var builder = WebApplication.CreateBuilder(args);

// Configure logging
builder.Host.ConfigureLogging(logging =>
{
    logging.ClearProviders();               // Clear default logging providers (like Console)
    logging.AddConsole();                   // Add Console logging
    logging.AddDebug();                     // Add Debug logging
    logging.SetMinimumLevel(LogLevel.Warning); // Set minimum log level to Warning
});

var app = builder.Build();

// Middleware pipeline
app.UseRouting();

app.MapGet("/", () => "Hello, World!");

app.Run();

Configure Logging via appsettings.json

Another common way to configure logging is by using the appsettings.json file. You can define logging settings in the Logging section of the configuration file. 

Example: Configure Logging in appsettings.json In your appsettings.json, you can define different logging levels for different providers (e.g., Console, Debug). json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Console": {
      "IncludeScopes": true
    }
  }
}

Note that in Program.cs, you don’t need to explicitly configure logging in the code if you are using appsettings.json. The default configuration of WebApplicationBuilder will pick up the logging settings from the configuration file.

var builder = WebApplication.CreateBuilder(args);

// No explicit logging configuration is needed in code since appsettings.json is used.

var app = builder.Build();

app.MapGet("/", () => "Hello, World!");

app.Run();

Add Custom Logging Providers e.g. Serilog

You can also add custom logging providers (e.g., Serilog, NLog, etc.) by using the ConfigureLogging method. 
Example: Add Serilog as a Custom Logger First, install the necessary Serilog NuGet packages:
  • Serilog.Extensions.Logging
  • Serilog.Settings.Configuration In Program.cs, configure Serilog as the logging provider:
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add Serilog as the logging provider
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)  // Read settings from appsettings.json
    .Enrich.FromLogContext()
    .WriteTo.Console()  // Write logs to Console
    .CreateLogger();

builder.Host.UseSerilog();  // Use Serilog as the logging provider

var app = builder.Build();

app.MapGet("/", () => "Hello, World!");

app.Run();

In appsettings.json, you can configure Serilog: json

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" }
    ]
  }
}

Configure Logging via Environment-Specific appsettings

You can also configure logging based on environments using appsettings.Development.json or appsettings.Production.json. This allows different logging configurations for different environments.

Example: Development-Specific Logging In appsettings.Development.json: json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information"
    }
  }
}

In appsettings.Production.json: json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Error"
    }
  }
}

ASP.NET Core will automatically pick the right configuration file based on the environment when you run the application.

Accessing the Logger in Application Code

Once logging is configured, you can access the logger in your application’s code by using Dependency Injection (DI) or directly through the ILogger interface.

Example: Injecting Logger in a Controller or Middleware
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", (ILogger<Program> logger) =>
{
    logger.LogInformation("Handling GET request for the root endpoint");
    return "Hello, World!";
});

app.Run();

Conclusion

  • You can configure logging in ASP.NET Core .NET 6+ using the WebApplication class either programmatically via Program.cs or declaratively via appsettings.json.
  • Use the Host property of WebApplicationBuilder for programmatic logging configuration.
  • For most applications, configuring logging via appsettings.json is a clean and effective way to manage logging levels and providers.
  • You can easily integrate third-party logging frameworks like Serilog or NLog for more advanced logging scenarios.

No comments:

Post a Comment

Hot Topics