skip to content

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%

answer

  1. catch host-startup failures
  2. ReloadableLogger: Reload then Freeze
  3. final logger completely replaces bootstrap
  4. ReadFrom.Configuration + ReadFrom.Services
  5. "The logger is already frozen"

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.

solid answer

~40 s

Configuring Serilog only inside the host means nothing is logged if the host fails to build - a bad configuration value, a DI validation error or a port that cannot be bound. Configuring it only up front means `appsettings.json` and DI are not available yet. The two-stage setup does both: `new LoggerConfiguration()...CreateBootstrapLogger()` creates a `ReloadableLogger` and assigns it to `Log.Logger`, and `builder.Services.AddSerilog((services, lc) => lc.ReadFrom.Configuration(builder.Configuration).ReadFrom.Services(services)...)` detects it. When the container first resolves the logger, the bootstrap logger is **reloaded** with the final configuration and **frozen**; loggers created during startup keep working. The final logger completely replaces the bootstrap configuration, so sinks you want in both must be declared twice. Keep `try`/`catch`/`finally` with `Log.CloseAndFlush()`, because in this path the factory does not dispose the logger.

go deeper

for a junior

Recall the shape: bootstrap logger first, try/catch around building the host, Log.CloseAndFlush in finally.

for a middle

Explain why startup failures need a logger before configuration exists, and that the final logger completely replaces the bootstrap one.

for a senior

Describe Reload and Freeze, ReadFrom.Services with singleton components, the frozen-logger failure with several hosts in one process, and who disposes the logger.

for a principal

Decide which startup failures must be captured where, such as a console sink for the platform versus a central store, so failed deployments are diagnosable.

## The chicken-and-egg problem A hotel-booking API wants its logging configured from `appsettings.json` (sinks, levels per environment) and from DI (an enricher that needs a service). Both only exist **after** `WebApplication.CreateBuilder` has run and the container is built. But the most important events of a failed deployment happen **before** that: a missing connection string throwing in `Program.cs`, `builder.Build()` failing DI validation, Kestrel failing to bind a port. Serilog's answer is two-stage initialization. ## Stage one: the bootstrap logger ```csharp Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .CreateBootstrapLogger(); ``` `CreateBootstrapLogger()` (from `Serilog.Extensions.Hosting`) builds a normal logger and wraps it in a **`ReloadableLogger`**. Anything can log through it immediately, including the `catch` block around host construction. ## Stage two: the final logger ```csharp try { var builder = WebApplication.CreateBuilder(args); builder.Services.AddSerilog((services, lc) => lc .ReadFrom.Configuration(builder.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext() .WriteTo.Console()); var app = builder.Build(); app.UseSerilogRequestLogging(); app.MapBookingEndpoints(); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "Hotel booking API failed to start"); } finally { Log.CloseAndFlush(); } ``` What happens, from the `AddSerilog` source: 1. At registration, `AddSerilog` checks whether `Log.Logger` is a `ReloadableLogger` (and `preserveStaticLogger` is false). The check is eager: replacing the bootstrap logger after this call is not supported. 2. When the container first resolves the Serilog logger (the logger factory needs it), it calls `Reload(...)` on the bootstrap logger with your callback, which disposes the bootstrap pipeline and creates the final one. 3. It then calls `Freeze()`. From now on the logger cannot be reconfigured and logging through it needs no synchronization. Loggers obtained during startup, including contextual ones, continue to work and now write through the final pipeline. 4. `Log.Logger` is set to the final logger, so static `Log` calls and request logging use it too. ## What the bootstrap logger catches The `catch` block logs through the bootstrap logger whenever the host cannot get going, for example: 1. code in `Program.cs` throwing before `Build()`, such as a required configuration value that is missing; 2. `builder.Build()` failing service validation, which the default builder enables in the Development environment; 3. `app.Run()` failing to start the server, for instance when the port is already in use. Without a logger at that point, the only trace would be whatever the process writes to standard error before it exits. ## "Completely replaces" The callback receives a **new** `LoggerConfiguration`; nothing from the bootstrap configuration carries over. In the example both stages call `WriteTo.Console()` and `Enrich.FromLogContext()` because each needs them. A sink present only in the bootstrap configuration simply stops receiving events once the host starts. ## ReadFrom.Services `ReadFrom.Services(services)` pulls Serilog components out of the container and adds them to the pipeline: | Registered service | Becomes | |---|---| | `LoggingLevelSwitch` | `MinimumLevel.ControlledBy(...)` | | `ILoggerSettings` | applied settings | | `IDestructuringPolicy` | `Destructure.With(...)` | | `ILogEventEnricher` | `Enrich.With(...)` | | `ILogEventFilter` | `Filter.With(...)` | | `ILogEventSink` | `WriteTo.Sink(...)` | So a `TenantEnricher` that needs another service can be registered with `AddSingleton<ILogEventEnricher, TenantEnricher>()` instead of being constructed by hand. These are resolved from the root provider, so register them as singletons. ## Traps - **Freezing twice.** `Freeze()` throws `InvalidOperationException` ("The logger is already frozen.") if the same bootstrap logger is frozen a second time - typically when several hosts in one process, such as parallel integration tests, capture the same static bootstrap logger. Use `preserveStaticLogger: true` or skip the bootstrap logger in tests. - **Disposal.** When a bootstrap logger is reloaded, the logger factory is told not to dispose it, so `Log.CloseAndFlush()` in `finally` is what flushes the final sinks. - **Configuration-only sinks.** A sink that exists only in `appsettings.json` is unavailable during stage one; startup failures are logged only to the bootstrap sinks.

  • The bootstrap logger writes to the console and the AddSerilog callback configures only a file sink. What does the console show after startup?
    Nothing more from Serilog. The callback starts from a fresh `LoggerConfiguration`, and the reloaded logger uses only what the callback declares, so the console sink stops at the moment the logger is reloaded. Add `WriteTo.Console()` to the callback as well if both stages should write there.
  • Why must services consumed through ReadFrom.Services be singletons?
    The final logger is built once, when the container first resolves it, from the root service provider, and it lives for the whole application. A scoped enricher or sink either fails scope validation (enabled by default in Development) or is resolved once from the root and shared for the application's life; a transient one is likewise created only once. Register Serilog components as singletons and inject longer-lived dependencies only.

The bootstrap logger is a temporary reception desk set up at the hotel door while the lobby is still being built: guests arriving early are still signed in. When the lobby opens, the permanent desk takes over with its own fittings - nothing from the temporary desk is moved across, and the temporary one is taken down for good.

  • The final logger inherits the bootstrap logger's sinks and adds its own
  • CreateBootstrapLogger is only needed for Windows services
  • ReadFrom.Services resolves scoped enrichers per request
  • Once AddSerilog is used, Log.CloseAndFlush in finally is unnecessary
  • A bootstrap logger can be reconfigured any number of times after the host starts

Assumes Serilog.AspNetCore and Serilog.Extensions.Hosting 10.0 on Serilog 4.4 with the ASP.NET Core 10 WebApplication builder; CreateBootstrapLogger and ReadFrom.Services come from Serilog.Extensions.Hosting.