Serilog.AspNetCore Documentation

repository·dev·Indexed 23 days ago

https://github.com/serilog/serilog-aspnetcore

Integration between Serilog and ASP.NET Core for structured logging of HTTP requests. Features include the RequestLoggingMiddleware for capturing request lifecycles, IDiagnosticContext for adding request-specific properties, and automatic TraceId and SpanId correlation.

Tokens
393
Snippets
1
Records
3
Agent score
31%

What's inside Serilog.AspNetCore

  1. Install Serilog.AspNetCore

    dev

    To use Serilog in your ASP.NET Core application, install the Serilog.AspNetCore NuGet package. Ensure you choose a version that matches your application's target framework (e.g., use an 8.x version for .NET 8.x).

    dotnet add package Serilog.AspNetCore
  2. How RequestLoggingMiddleware works

    dev

    The RequestLoggingMiddleware is the core component used to log HTTP requests in ASP.NET Core. It intercepts incoming requests, starts a DiagnosticContext collection, and upon request completion (or failure), uses a MessageTemplate and properties gathered during the request lifecycle to emit a single structured log event.

    Key behaviors:

    • Diagnostic Context: It uses IDiagnosticContext to allow other parts of your application (like controllers or services) to push properties into the current request's log event.
    • Lifecycle: It measures elapsed time, captures the HTTP status code, and handles exceptions by logging them with a 500 status code.
    • Trace Integration: It automatically captures TraceId and SpanId from Activity.Current if available, ensuring logs are correlated with distributed traces.
    • Customization: The logging behavior (level, message template, property extraction, and context enrichment) is driven by RequestLoggingOptions.
  3. Configure Serilog in ASP.NET Core

    dev
    To integrate Serilog, configure the initial logger in Program.cs using a try/catch block to capture startup errors, and then call builder.Services.AddSerilog() to redirect all ASP.NET Core log events through the Serilog pipeline. Finally, remove the default `