MSDN Documentation

.NET Web Development

Web Logging in .NET

Effective logging is crucial for building robust and maintainable web applications. It provides insights into application behavior, helps diagnose issues, and enables performance monitoring. This documentation covers logging fundamentals within the .NET ecosystem for web development.

Basic Logging with `Microsoft.Extensions.Logging`

The built-in logging abstraction in .NET, `Microsoft.Extensions.Logging`, offers a flexible and extensible way to log messages. It decouples the logging code from the specific logging provider implementation.

To start, you typically inject an `ILogger` instance into your components (like controllers or services):


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Entering the Index action.");
        // Your action logic here
        return View();
    }

    public IActionResult About()
    {
        _logger.LogWarning("Accessing the About page.");
        return View();
    }

    public IActionResult Error()
    {
        _logger.LogError("An unexpected error occurred.");
        return View();
    }
}
            

The `ILogger` interface provides methods for different log levels, such as `LogInformation`, `LogWarning`, `LogError`, `LogDebug`, and `LogCritical`.

Integrating Logging Providers

The `Microsoft.Extensions.Logging` abstraction itself doesn't write logs anywhere. It requires one or more logging providers to be configured. Popular providers include:

In ASP.NET Core, logging is configured in the `Program.cs` or `Startup.cs` file. Here's an example using the Console provider:


// Program.cs in .NET 6+
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Configure logging (default is Console and Debug)
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug(); // Optional, often default

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
            

Logging Configuration

Logging levels can be configured to control the verbosity of logs. You can set default levels and override them for specific categories (namespaces or types).

Using `appsettings.json` (for ASP.NET Core):


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
            

In code, you can also set logging filters:


builder.Logging.SetMinimumLevel(LogLevel.Debug); // Set minimum level for all providers
builder.Logging.AddFilter("Microsoft", LogLevel.Warning); // Override for Microsoft namespaces
builder.Logging.AddFilter("MyApplication.Services", LogLevel.Information);
            

Advanced Scenarios

Structured Logging

Modern logging often involves structured logging, where messages are logged as key-value pairs rather than plain text. This makes logs machine-readable and easier to query. Providers like Serilog excel at this.

Correlation IDs

To track a single request across multiple services or components, use correlation IDs. These are typically generated at the edge of your system and passed along with every log message related to that request.

Custom Log Categories

You can create loggers with specific categories to fine-tune filtering and routing:


var dbLogger = _loggerFactory.CreateLogger("MyApplication.Database");
dbLogger.LogDebug("Executing SQL query: SELECT * FROM Users");
            

Best Practices for Web Logging