Logging
suggest changeModern .NET applications utilize the unified logging abstraction provided by Microsoft.Extensions.Logging. It integrates with the .NET dependency injection system and supports structured logging, log levels, scopes, and third-party providers (such as Serilog, NLog, or Application Insights).
Core Concepts and Log Levels
The ILogger<TCategoryName> interface is injected into classes to write log entries. .NET defines six severity levels:
| Level | Method | Purpose |
|---|---|---|
Trace |
LogTrace |
Most detailed messages; typically disabled in production |
Debug |
LogDebug |
Useful for development and debugging |
Information |
LogInformation |
Tracks normal application flow (e.g., service started, order placed) |
Warning |
LogWarning |
Abnormal or unexpected events that do not halt execution |
Error |
LogError |
Failures in current operation or unhandled exceptions |
Critical |
LogCritical |
Severe system-wide failure requiring immediate intervention |
Structured Logging (Message Templates)
Always use message templates with named placeholders rather than string interpolation ($""). Structured logging preserves parameter values as individual queryable properties when exported to tools like Elasticsearch, Seq, or CloudWatch:
using Microsoft.Extensions.Logging;
public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public void ProcessOrder(int orderId, string customerId, decimal amount)
{
// Recommended: Structured logging with named placeholders
_logger.LogInformation(
"Processing order {OrderId} for customer {CustomerId} with amount {Amount:C}",
orderId, customerId, amount
);
try
{
// Execute business logic...
}
catch (Exception ex)
{
// Pass the exception as the first argument to capture full callstack
_logger.LogError(ex, "Failed to process order {OrderId}", orderId);
throw;
}
}
}
Configuring Logging in appsettings.json
Control verbosity dynamically per namespace or category without modifying code:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"MyApp.Services": "Debug"
}
}
}
High-Performance Logging with Source Generators
For performance-critical code paths, string formatting and boxing parameters can create garbage collection pressure. Modern .NET provides the [LoggerMessage] source generator to generate zero-allocation logging methods at compile time:
using Microsoft.Extensions.Logging;
public static partial class LogExtensions
{
// The source generator produces an optimized, allocation-free implementation
[LoggerMessage(
EventId = 1001,
Level = LogLevel.Information,
Message = "User {UserId} logged in from IP {IpAddress}"
)]
public static partial void UserLoggedIn(
this ILogger logger,
int userId,
string ipAddress
);
}
// Usage:
// logger.UserLoggedIn(42, "192.168.1.100");
Logging Scopes for Contextual Data
Scopes attach contextual metadata (such as TransactionId or TenantId) to all log messages written within a block:
public async Task HandleRequestAsync(string transactionId)
{
using (_logger.BeginScope(new Dictionary<string, object>
{
["TransactionId"] = transactionId,
["Environment"] = "Production"
}))
{
_logger.LogInformation("Validating payload");
_logger.LogInformation("Executing database update");
// All messages inside this block automatically include TransactionId and Environment
}
}
Console Configuration in Generic Host / Web API
In minimal APIs or console applications, logging is pre-configured by default:
var builder = WebApplication.CreateBuilder(args);
// Configure additional providers if needed
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
var app = builder.Build();