skip to content

Serilog

Serilog is structured .NET logging: message templates keep named properties, enrichers add context, and sinks ship events to files and log servers. Interviewers ask why templates beat interpolation.

on this pageshow

explore

questions

15

In an ASP.NET Core 10 app, what does builder.Services.AddSerilog() change about ILogger<T> logging, and what happens to the Logging section and built-in providers?

level: juniorimportance: must knowfreq 65%

answer

  1. package Serilog.AspNetCore
  2. replaces the ILoggerFactory singleton
  3. category becomes SourceContext
  4. Logging:LogLevel no longer applies
  5. writeToProviders: true to keep providers

basics

~20 s

AddSerilog() registers Serilog's ILoggerFactory, so every ILogger<T> writes through the Serilog pipeline, with the category as SourceContext. Levels then come from Serilog's MinimumLevel and overrides; the Logging section and the built-in console and debug providers are bypassed.

solid answer

~40 s

`Serilog.AspNetCore` (whose dependencies bring in `Serilog.Extensions.Hosting`, the console, file and debug sinks, compact JSON formatting and `Serilog.Settings.Configuration`) adds `AddSerilog` to `IServiceCollection`. It registers a singleton `ILoggerFactory` implemented by `SerilogLoggerFactory`, which replaces the default factory, so every `ILogger<T>` from ASP.NET Core, EF Core or your own code becomes a Serilog event whose `SourceContext` is the category name. The parameterless `AddSerilog()` uses the static `Log.Logger`; the overloads taking a configuration callback build the logger inside the container. Because the default factory is gone, the `Logging:LogLevel` section no longer filters anything - use Serilog's `MinimumLevel` and `Override` instead - and the built-in console, debug and event-source providers receive nothing unless you pass `writeToProviders: true`. Every overload registers `IDiagnosticContext` as a singleton; the overloads that receive or build a logger also register Serilog's own `ILogger`.

go deeper

for a junior

Know the package and the one line: builder.Services.AddSerilog(), after which injected ILogger<T> writes to Serilog's sinks.

for a middle

Explain that AddSerilog replaces the ILoggerFactory, why the Logging section stops working, and that the category becomes SourceContext for overrides.

for a senior

Choose between the overloads by who owns and disposes the logger, and know when writeToProviders or preserveStaticLogger is needed.

for a principal

Decide whether one logging pipeline replaces Microsoft.Extensions.Logging providers across services, and how that affects vendor integrations and configuration conventions.

## Two logging systems, one pipeline ASP.NET Core logs through **Microsoft.Extensions.Logging** (MEL): code asks for `ILogger<T>`, a logger factory creates it, and registered providers (console, debug, event source, and event log on Windows, all added by the default host) write the output, filtered by the `Logging` configuration section. **Serilog** is a separate library with its own pipeline. `Serilog.AspNetCore` connects them so that framework events and your own events land in the same Serilog sinks, with the same levels and enrichers. ```bash dotnet add package Serilog.AspNetCore ``` The package depends on `Serilog`, `Serilog.Extensions.Hosting`, `Serilog.Settings.Configuration`, `Serilog.Formatting.Compact` and the console, file and debug sinks, so a typical app needs nothing else. Its version tracks `Microsoft.Extensions.Hosting`: a .NET 10 app uses Serilog.AspNetCore 10.x. ## What AddSerilog registers `builder.Services.AddSerilog(...)` comes from `Serilog.Extensions.Hosting`. Depending on the overload it registers: - a singleton **`ILoggerFactory`** implemented by `SerilogLoggerFactory` - the key step; - the Serilog `ILogger` itself, for code that wants Serilog's API directly - registered by the overloads that receive or build a logger, not by the parameterless one; - **`IDiagnosticContext`** (and the concrete `DiagnosticContext`) as singletons, used by request logging. The default host registered MEL's `LoggerFactory` with a try-add; the later registration is the one the container resolves, so `ILogger<T>` (which is created through `ILoggerFactory`) now wraps Serilog. Each category name, such as `Microsoft.AspNetCore.Hosting.Diagnostics` or `HotelBooking.Api.BookingsController`, becomes the event's `SourceContext`, which is what Serilog's `MinimumLevel.Override` matches. ## The overloads | Call | Logger used | Who disposes it | |---|---|---| | `AddSerilog()` | the static `Log.Logger`, configured before the host | you, with `Log.CloseAndFlush()` | | `AddSerilog(logger, dispose: true)` | the instance you pass | the factory, on host shutdown | | `AddSerilog(lc => ...)` or `AddSerilog((services, lc) => ...)` | built inside the container; also assigned to `Log.Logger` unless `preserveStaticLogger: true` | the factory, through `Log.CloseAndFlush()`, unless it froze a bootstrap logger | `builder.Host.UseSerilog(...)` on `IHostBuilder` still exists and simply calls `AddSerilog`; the package README now shows `builder.Services.AddSerilog()`. ## What stops working Because MEL's own `LoggerFactory` is no longer used: 1. **The `Logging` section is ignored.** `"Logging": { "LogLevel": { "Default": "Warning" } }` no longer filters anything; the README tells you to remove it. Express the same intent as `"Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft.AspNetCore": "Warning" } } }`. 2. **Built-in providers go quiet.** `AddConsole()`, `AddDebug()` and the rest are still registered but receive no events. Pass `writeToProviders: true` if some MEL provider must keep receiving events; Serilog then forwards to the registered providers. 3. **`builder.Logging.SetMinimumLevel(...)` has no effect** on what Serilog writes, for the same reason. What keeps working: `ILogger<T>` injection, message templates with named holes, `BeginScope` properties (carried into the event when the Serilog configuration has `Enrich.FromLogContext()`), and every library that logs through MEL. ## Checking the wiring Two quick checks confirm that framework events now flow through Serilog: - Add `{SourceContext}` to the console sink's output template for a while, as the Serilog.AspNetCore README suggests; lines from Kestrel, routing and your controllers then show their category names, which are also the names to use in `Override`. - Change a Serilog override, for example `Microsoft.AspNetCore` to `Warning`, and watch the framework's Information lines disappear; changing `Logging:LogLevel` should visibly do nothing. Application code can keep injecting `ILogger<T>`, which is the usual choice because libraries and framework code use it too. Code that wants Serilog-specific features, such as `ForContext` with `destructureObjects`, can use the static `Log` class or the Serilog `ILogger` the callback overloads register. ## A hotel-booking API set up minimally ```csharp using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); try { var builder = WebApplication.CreateBuilder(args); builder.Services.AddSerilog(); var app = builder.Build(); app.MapGet("/api/hotels/{id}", (int id, ILogger<Program> log) => { log.LogInformation("Hotel {HotelId} viewed", id); return Results.Ok(); }); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } ``` The `LogInformation` call reaches the Serilog console sink with `SourceContext` = `Program` and a `HotelId` property.

  • After switching to Serilog, the team still edits Logging:LogLevel to quiet EF Core and nothing changes. Why, and what is the fix?
    The `Logging` section is read by MEL's `LoggerFactory`, which `AddSerilog` replaced with `SerilogLoggerFactory`. Serilog decides levels with its own `MinimumLevel`, so add `"Microsoft.EntityFrameworkCore": "Warning"` under `Serilog:MinimumLevel:Override` and delete the dead `Logging` section to avoid confusion.
  • When would you pass writeToProviders: true?
    When some Microsoft.Extensions.Logging provider must keep receiving events alongside Serilog's sinks - for example a vendor provider that has no Serilog sink. Serilog then forwards events to the registered `ILoggerProvider`s. Without it, those providers stay registered but silent.

  • The Logging:LogLevel section still filters events after AddSerilog
  • AddSerilog adds Serilog as one more provider next to the console provider
  • Only Serilog's static Log class can write to Serilog sinks; ILogger<T> cannot
  • builder.Logging.SetMinimumLevel controls what Serilog writes
  • Serilog.AspNetCore requires separately installing the console and file sinks

Assumes Serilog.AspNetCore 10.0 (tracking Microsoft.Extensions.Hosting 10) on Serilog 4.4 and ASP.NET Core 10; AddSerilog on IServiceCollection lives in Serilog.Extensions.Hosting.

open as a page

In Serilog 4, how do you build a LoggerConfiguration that writes to the console and a daily file, and what is the default minimum level?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Chain new LoggerConfiguration(), WriteTo.Console() and WriteTo.File(path, rollingInterval: RollingInterval.Day), then CreateLogger(), after adding Serilog.Sinks.Console and Serilog.Sinks.File. With no MinimumLevel call, Information and above pass; Debug and Verbose are dropped.

open as a page

In Serilog, how does Log.Information("Shipment {TrackingNumber} picked up by {CourierId}", number, courierId) bind its arguments, and why is an interpolated string wrong?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Serilog parses the template, then assigns the arguments to its named holes in order: number becomes TrackingNumber, courierId becomes CourierId. An interpolated string bakes the values into the template text: no properties, and a new template per value.

open as a page

What does Serilog.AspNetCore's UseSerilogRequestLogging() log for each request, at which level, and why does its position in the middleware pipeline matter?

level: middleimportance: must knowfreq 60%

basics

~20 s

It writes one event per request: "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms", at Error when an exception escapes or the status exceeds 499, else Information. It only times and logs middleware registered after it.

open as a page

In a Serilog message template, how do {Shipment}, {@Shipment} and {$Shipment} differ, and what does @ cost on a large object?

level: middleimportance: must knowfreq 60%

basics

~10 s

Plain {Shipment} keeps scalars and collections but stores ToString() for other objects; {@Shipment} destructures public properties recursively, to depth 10; {$Shipment} always stores ToString(). @ costs reflection, every getter run, and graph-sized payloads.

open as a page

Why can a Serilog-based .NET app lose its last log events on exit or after a crash, and how does Log.CloseAndFlushAsync() prevent it?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Batched, buffered and async sinks hold events in memory and write them later, so exiting without disposing the logger abandons them. Log.CloseAndFlushAsync() disposes the static logger, draining those sinks, and resets Log.Logger; await it in finally.

open as a page

With Serilog.AspNetCore, how do IDiagnosticContext.Set and RequestLoggingOptions.EnrichDiagnosticContext add user and tenant ids to the single request completion event?

level: middleimportance: should knowfreq 45%

basics

~10 s

Inject IDiagnosticContext and call Set("BookingId", id) during the request, or set common values centrally in RequestLoggingOptions.EnrichDiagnosticContext; both become properties of that request's one completion event only, not of other log events.

open as a page

With Serilog.Settings.Configuration, how is the "Serilog" section of appsettings.json read, and which parts of it change at runtime when the file is edited?

level: middleimportance: should knowfreq 55%

basics

~20 s

ReadFrom.Configuration(configuration) maps the Serilog section onto LoggerConfiguration: WriteTo entries become sink method calls with Args as named parameters, MinimumLevel becomes levels and overrides. On reload, only existing level values change; new Override keys and sink changes need a restart.

open as a page

In Serilog, how do MinimumLevel.Override, a sink's restrictedToMinimumLevel and a LoggingLevelSwitch decide whether an event from a given SourceContext is written?

level: middleimportance: should knowfreq 50%

basics

~20 s

MinimumLevel.Override sets the effective minimum for events whose SourceContext starts with a namespace, replacing the default level. A sink's restrictedToMinimumLevel filters further but cannot let through events the logger dropped. A LoggingLevelSwitch makes either level changeable at runtime.

open as a page

When a Serilog sink silently writes nothing, how does SelfLog help you find out why, and what kinds of problems does it report?

level: middleimportance: should knowfreq 30%

basics

~20 s

Serilog never lets a logging failure throw into the app; it reports it to SelfLog, which is off by default. Calling SelfLog.Enable(Console.Error) before the logger is built prints misnamed sinks, unopenable files and sink exceptions.

open as a page

In Serilog, how do Enrich.WithProperty, ForContext and LogContext.PushProperty attach a property such as a shipment id, and why does PushProperty need Enrich.FromLogContext()?

level: middleimportance: should knowfreq 50%

basics

~20 s

Enrich.WithProperty adds a fixed property to every event, ForContext returns a logger whose events carry it, and LogContext.PushProperty adds it to all events in an async scope until disposed. PushProperty only reaches events if Enrich.FromLogContext() is configured.

open as a page

Why does Serilog.AspNetCore recommend CreateBootstrapLogger() followed by AddSerilog((services, lc) => ...), and what happens to the bootstrap logger once the host starts?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A bootstrap logger exists before the host, so failures while building it are still logged; the final logger, configured once configuration and DI exist, then completely replaces it. CreateBootstrapLogger() returns a ReloadableLogger that AddSerilog reloads and freezes.

open as a page

With Serilog.Sinks.File, how do rollingInterval, fileSizeLimitBytes, rollOnFileSizeLimit and retainedFileCountLimit interact, and why can a plain WriteTo.File("log.txt") stop logging?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Serilog.Sinks.File caps each file at 1 GB by default. Without rollingInterval or rollOnFileSizeLimit there is no roll point, so a full log.txt silently drops new events. Rolling creates a file set; retainedFileCountLimit (31) prunes the oldest.

open as a page

How do you stop Serilog from logging a shipment's recipient details or its whole object graph, using Destructure.ByTransforming, the size limits and a custom IDestructuringPolicy?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Register Destructure.ByTransforming<Shipment>(s => new { s.TrackingNumber, s.Status }) so {@Shipment} logs only safe fields, cap graphs with ToMaximumDepth, ToMaximumStringLength and ToMaximumCollectionCount, and write an IDestructuringPolicy for rules across many types. None of these affect {Shipment} without @.

open as a page

What does Serilog.Formatting.Compact's CompactJsonFormatter write for each event, and when would you choose RenderedCompactJsonFormatter or the core JsonFormatter instead?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

CompactJsonFormatter writes one JSON object per line: @t, @mt, @r for formatted holes, @l (omitted for Information), @x, @tr/@sp, then every property at the top level. RenderedCompactJsonFormatter writes a rendered @m and an @i event id instead of @mt.

open as a page