Skip to content

Logging in ASP.NET Core

1. Introduction to Logging in ASP.NET Core ASP.NET Core logging is built into the framework from day one — no third-party package required to get started. The system is built around three abstractions that compose cleanl...

Ekanatha Reddy Urivakili9 min1,044 words

1. Introduction to Logging in ASP.NET Core

ASP.NET Core comes with a flexible, extensible logging framework integrated from the ground up—no third-party packages required to get started. At its heart is a design focused on a clean separation of concerns with three key abstractions:

  • Loggers: Components that application code interacts with to write logs (ILogger<T>).
  • Providers: Responsible for sending log entries to various destinations (console, files, external services like Seq or Splunk).
  • Log Levels: Control what gets recorded based on severity (Debug, Information, Warning, Error, Critical).

This architecture ensures that your application code never depends on any specific logging library or sink. You simply write logs through generic interfaces, and the plumbing underneath handles routing and formatting.

flowchart LR
    APP["Your app code"]
    ILogger["ILogger<T> / ILogger"]
    LoggerFactory["LoggerFactory"]
    Providers["Logging Providers"]
    Sinks["Console / File / Seq / Splunk / etc."]

    APP --> ILogger
    ILogger --> LoggerFactory
    LoggerFactory --> Providers
    Providers --> Sinks

Figure 1: ASP.NET Core Logging High-Level Flow

Your application code depends only on ILogger abstraction, which obtains logger instances from the factory. Providers bind concrete sinks at application startup, allowing you to swap destinations by configuration without touching business logic.


2. Getting Started: Using the WebApplication Logger

In minimal APIs, the simplest access point is app.Logger directly available after WebApplication.Create(). This logger is created behind the scenes and configured with default providers, such as the Console logger.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Logger.LogInformation("Application starting on {Env}", app.Environment.EnvironmentName);

app.MapGet("/orders/{id}", (Guid id) =>
{
    app.Logger.LogDebug("Fetching order {OrderId}", id);
    return Results.Ok(new { id });
});

app.Logger.LogInformation("Listening on {Urls}", string.Join(", ", app.Urls));
app.Run();

What to notice: app.Logger uses a generic category name Microsoft.AspNetCore.Builder.WebApplication, simplifying startup logging but not ideal for granular filtering.

While this is fine for simple or startup code, for more complex applications inject ILogger<T> per class to get category names matching your type names, improving searching and filtering in logs.


3. Understanding ILoggerFactory and Its Role

ILoggerFactory is the central factory responsible for creating ILogger instances. It is registered in the DI container and manages the lifecycle of logging providers.

You rarely use ILoggerFactory directly in business code, but understanding it adds clarity:

  • It wires up logging providers based on your IConfiguration.
  • It creates loggers either by generic types or explicit category names.
  • It allows dynamic programmatic control over logging behavior.

Usage examples

// Configure logging providers at startup
var builder = WebApplication.CreateBuilder(args);
builder.Logging
       .ClearProviders()
       .AddConsole()
       .AddDebug()
       .SetMinimumLevel(LogLevel.Information);

// Use factory in an infrastructure class where DI on ILogger<T> isn't possible
public class OrderEventBus
{
    private readonly ILogger _logger;

    public OrderEventBus(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger("OrderEventBus");
    }

    public void Publish(object @event)
    {
        _logger.LogInformation("Publishing event {EventType}", @event.GetType().Name);
    }
}

// In unit tests, create an ILoggerFactory manually without dependency injection
using var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
    loggingBuilder.AddConsole();
    loggingBuilder.SetMinimumLevel(LogLevel.Debug);
});

var logger = loggerFactory.CreateLogger<OrderService>();
var sut = new OrderService(logger /*, other dependencies */);

What to notice: ILoggerFactory.CreateLogger lets libraries avoid DI and still participate in consistent logging pipelines, useful in hosted services and background jobs.


4. Core Logging: Using ILogger and Message Templates

The preferred logger type to inject everywhere is ILogger<T>. The type parameter T defines the category name for the logger, which is typically the fully qualified class name like "MyApp.Services.OrderService". This enhances log filtering, monitoring, and diagnostics.

Example: Controller logging with ILogger<T>

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly ILogger<OrdersController> _logger;
    private readonly IOrderService _service;

    public OrdersController(ILogger<OrdersController> logger, IOrderService service)
    {
        _logger = logger;
        _service = service;
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetOrder(Guid id, CancellationToken ct)
    {
        _logger.LogInformation("Fetching order {OrderId}", id);

        var order = await _service.GetOrderAsync(id, ct);

        if (order is null)
        {
            _logger.LogWarning("Order {OrderId} not found", id);
            return NotFound();
        }

        return Ok(order);
    }
}

The golden rule: use message templates, not string interpolation

Incorrect approach:

_logger.LogInformation($"Order {orderId} placed by {userId}"); // Do NOT do this
  • String interpolation destructures the message into a single formatted string.
  • This loses structured data benefits; you cannot filter by OrderId.

Correct approach:

_logger.LogInformation("Order {OrderId} placed by {UserId}", orderId, userId);
  • The named placeholders become named properties attached to the log event.
  • Structured logging enables powerful querying in centralized logging tools (Seq, Splunk, ELK).

Advanced: Scopes for Contextual Logging

Scopes allow propagating contextual information across multiple log calls. Data included in a scope is attached as properties to every log within the defined lifetime.

public async Task ProcessOrderAsync(Guid orderId, CancellationToken ct)
{
    using (_logger.BeginScope(new Dictionary<string, object>
    {
        ["OrderId"] = orderId,
        ["UserId"]  = _currentUser.Id
    }))
    {
        _logger.LogInformation("Starting order processing");
        await ValidateAsync(orderId, ct);
        _logger.LogInformation("Validation passed");
        await ChargeAsync(orderId, ct);
        _logger.LogInformation("Payment complete");
    }
}

What to notice: OrderId and UserId are added to every log inside the scope transparently, enabling easy correlation without passing parameters explicitly.


Optimizing performance with [LoggerMessage] source generator

For performance-sensitive code paths (e.g., logging in tight loops or hot paths), the [LoggerMessage] attribute lets the compiler generate high-efficiency logging methods to avoid allocations.

public partial class OrderService
{
    private readonly ILogger<OrderService> _logger;

    [LoggerMessage(Level = LogLevel.Information,
                   Message = "Order {OrderId} dispatched to warehouse {WarehouseId}")]
    private partial void LogOrderDispatched(Guid orderId, string warehouseId);

    [LoggerMessage(Level = LogLevel.Error,
                   Message = "Payment failed for order {OrderId} after {Attempts} attempts")]
    private partial void LogPaymentFailed(Guid orderId, int attempts);

    public async Task DispatchAsync(Order order)
    {
        LogOrderDispatched(order.Id, order.WarehouseId); // zero allocations
    }
}

What to notice: This eliminates boxing and string.Format calls on every log call, improving throughput and reducing GC pressure.

How [LoggerMessage] works internally

This source generator scans your partial class, generates private static readonly delegate fields and efficient methods, and uses them to write logs, all determined at compile-time.


5. Configuring Log Levels and Filtering

ASP.NET Core logging is level-driven, where only messages at or above a configured minimum severity are emitted. Configuring log levels carefully allows filtering noise while retaining actionable data.

The level hierarchy: Trace < Debug < Information < Warning < Error < Critical < None

Per-category filtering hierarchy

The logging system searches the category-tree for the most specific log level rule applying to the message's category:

flowchart TD
    Root["Default Log Level"]
    Microsoft["Microsoft (Warning)"]
    AspNetCore["Microsoft.AspNetCore (Error)"]
    EntityFramework["Microsoft.EntityFrameworkCore (Debug)"]
    MyAppOrders["MyApp.Orders (Information)"]
    MyApp["MyApp (Debug)"]

    Root --> Microsoft
    Microsoft --> AspNetCore
    Microsoft --> EntityFramework
    Root --> MyApp
    MyApp --> MyAppOrders

Figure 2: Category-based log level hierarchy


Sample appsettings.json logging section

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.AspNetCore": "Error",
      "Microsoft.EntityFrameworkCore": "Debug",
      "System": "Error",
      "MyApp": "Debug",
      "MyApp.Orders": "Information"
    },
    "Console": {
      "FormatterName": "json",
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

Note:

  • You can override log levels globally and per category.
  • Each provider (e.g., Console) can have its own log level filter.
  • The "most-specific-wins" rule means the deepest matching category applies.

Environment-Specific Overrides and 12-Factor Approach

Use appsettings.{Environment}.json files for environment specific changes:

// appsettings.Development.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

For containerized deployments, override via environment variables, replacing : with double underscores:

Logging__LogLevel__Default=Warning
Logging__LogLevel__MyApp=Debug
Logging__LogLevel__Microsoft.EntityFrameworkCore=Warning

This enhances portability, favoring immutable config in containers.


Programmatic Control At Runtime

You can also filter logs programmatically for dynamic behaviors:

builder.Logging.AddFilter((provider, category, level) =>
{
    if (category.StartsWith("Microsoft.EntityFrameworkCore.Database.Command"))
        return provider.Contains("Debug") && level >= LogLevel.Information;

    return level >= LogLevel.Warning;
});

Such filters can be useful in advanced scenarios, adjusting logging without config file changes.


Choosing the Right Logger: Decision Table

ScenarioRecommended Logger
Minimal API / startup codeapp.Logger
Services, controllers, handlersILogger<T> via DI
Libraries/infrastructure needsILoggerFactory.CreateLogger("name")
Unit testsLoggerFactory.Create(...) or NullLogger<T>.Instance
Hot path (>10k calls/sec)[LoggerMessage] source generator

6. Observability: What to Log and How

Logging is the backbone of observability but best practices help you get actionable signals without noise.

What to log

  • Startup and shutdown events: App lifecycle signals.
  • Request start and end: Correlate logs with HTTP trace.
  • Warnings and errors: Always capture these with context.
  • Structured events: User actions, state changes, method entries/exits.
  • Performance markers: Duration of important operations.
  • Failures & retries: Log failed calls with error details and retry attempts.

Use message templates consistently to produce structured logs for querying.


Example: Structured log line in JSON

{
  "Timestamp": "2024-06-01T12:34:56.789Z",
  "LogLevel": "Information",
  "Category": "MyApp.Services.OrderService",
  "Message": "Order {OrderId} dispatched to warehouse {WarehouseId}",
  "OrderId": "d87d2a10-4a9b-46ab-bf01-870c2d793f1a",
  "WarehouseId": "WH-225",
  "RequestId": "e5c2d4f2-1cbe-468a-9a29-23d8b3b44f74",
  "Service": "OrderService"
}

Structured logs enable slicing by any property like OrderId or WarehouseId.


Key Metrics: RED and USE Patterns

MetricPurposeCollection Method
Requests / ThroughputNumber of requests served per secondApplication Metrics, Counters
ErrorsRate of failed requestsLog aggregates, Error counters
DurationLatency distribution per requestTiming spans, traces
CPU, Memory, Disk UtilizationResource consumptionPlatform metrics, telemetry
Queue LengthBacklog size or async pipeline loadMetrics and logs

A combination of logs and metrics supplies holistic observability.


Distributed Tracing with OpenTelemetry

Integrate OpenTelemetry .NET SDK to trace requests:

// Program.cs snippet
builder.Services.AddOpenTelemetryTracing(builder => builder
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddConsoleExporter());

Correlate traces with logs via consistent TraceId and SpanId distributed as log scope properties.


Sample SLI/SLO and Alerting Table

SLI MetricSLO TargetAlert Condition
Request success rate>= 99.9%< 99.8% over 5 mins, page on-call
P99 request latency< 300 ms> 400 ms sustained 5 mins
Error rate< 0.1%> 0.5% over 5 mins, page on-call
Logs emitted / secondBaseline ± 50%Sudden drop/rise indicating outage

SLIs instrument reliability, latency, and availability, the pillars of observability.


7. Sequence Diagrams Illustrating Logging Interactions

Sequence: Logging a Request in ASP.NET Core

sequenceDiagram
    participant Client
    participant ASPNETCore
    participant Logger as ILogger<T>
    participant LoggerFactory
    participant Provider
    participant Sink

    Client->>ASPNETCore: Send HTTP request
    ASPNETCore->>Logger: Log "Request started"
    Logger->>LoggerFactory: Create ILogger<T> if needed
    Logger->>Provider: Send log entry
    Provider->>Sink: Write to console/file/etc.
    ASPNETCore->>Logger: Log "Request ended"
    Logger->>Provider: Send end log entry

Figure 3: Typical request logging flow


Summary

ASP.NET Core offers a full-featured, composable logging framework suitable for everything from tiny minimal APIs to complex distributed microservices.

StrengthDetail
Built-in, no dependenciesStart logging with just Microsoft.Extensions.Logging
Provider-based architectureSwap sinks without changing app code
Structured loggingUse message templates, scopes, and ILogger<T> categories
PerformanceOptimize hot paths with [LoggerMessage] source generator
ConfigurationFine-grained category-based filtering with environment overrides
Observability integrationCombine with tracing and metrics for production diagnostics

Reference: Microsoft Docs: Logging in .NET and ASP.NET Core


Your next steps:

  • Replace any ad-hoc Console.WriteLine with structured logging.
  • Use scopes to enrich request context.
  • Consider [LoggerMessage] for hot paths.
  • Configure log levels carefully per environment.
  • Integrate logs and traces in your monitoring pipeline.