skip to content

Sinks & Settings

Building a Serilog pipeline: LoggerConfiguration with WriteTo sinks, MinimumLevel overrides per source, and the Serilog section in appsettings. Interviewers ask why logs vanish without CloseAndFlush.

on this pageshow

explore

questions

6

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%

answer

  1. fluent builder ending in CreateLogger()
  2. sinks ship as separate NuGet packages
  3. WriteTo.Console() and WriteTo.File(path, ...)
  4. rollingInterval: RollingInterval.Day
  5. default minimum level: Information

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.

solid answer

~30 s

A Serilog pipeline is built with the fluent `LoggerConfiguration`: `MinimumLevel` sets the threshold, each `WriteTo.X()` adds a sink, and `CreateLogger()` returns a `Logger` that you usually assign to `Log.Logger`. Sinks are not in the core `Serilog` package: `WriteTo.Console()` comes from `Serilog.Sinks.Console` and `WriteTo.File()` from `Serilog.Sinks.File`. `WriteTo.File("logs/callcentre-.txt", rollingInterval: RollingInterval.Day)` writes one file per day, with the date inserted before the extension. If you never call `MinimumLevel`, the logger's minimum is `Information`, so `Log.Debug` and `Log.Verbose` calls are discarded before any sink sees them. Until `Log.Logger` is assigned it is a silent logger, so early events go nowhere.

code

bash · 3 lines
bash
dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File

go deeper

for a junior

Write the builder from memory: LoggerConfiguration, WriteTo.Console, WriteTo.File with RollingInterval.Day, CreateLogger, and assignment to Log.Logger. Name the two sink packages.

for a middle

Explain the Information default and why a Debug call vanishes, the difference between the logger minimum and a sink's restrictedToMinimumLevel, and the default output templates.

for a senior

Point out the silent Logger.None before assignment, the single-use CreateLogger, and that the logger owns and must dispose its sinks so file buffers are flushed on exit.

for a principal

Frame code-built configuration against appsettings-driven configuration: code is compile-checked, while configuration lets operations change sinks and levels per environment without a rebuild.

## What a Serilog pipeline is **Serilog** is a structured logging library for .NET. You describe a logging pipeline once with a fluent builder, `LoggerConfiguration`, and get back an `ILogger` that every log call goes through. The pipeline has three kinds of parts: - a **minimum level** - events below it are thrown away immediately, before any work is done on them; - **sinks** - destinations such as the console, a file or a log server, added with `WriteTo`; - optional enrichers, filters and destructuring rules, which other parts of the tree cover. `CreateLogger()` turns the configuration into a `Serilog.Core.Logger`. You can inject that object, or assign it to the static `Log.Logger` so that `Log.Information(...)` anywhere in the app uses it. ## A console plus daily-file logger for a call-centre app ```csharp using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File("logs/callcentre-.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); Log.Information("Call centre started"); ``` With `RollingInterval.Day`, the file sink inserts the date (format `yyyyMMdd`) before the extension, so the app writes `logs/callcentre-20261007.txt` today and a new file tomorrow. ## Sinks are separate packages The core `Serilog` package holds the builder, the levels, the event model and the plumbing sinks (aggregates, filters, batching), but no console or file output of its own. Each sink is its own NuGet package that adds an extension method to `WriteTo`: | Method | Package | Default output template | |---|---|---| | `WriteTo.Console()` | `Serilog.Sinks.Console` | `[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}` | | `WriteTo.File(path)` | `Serilog.Sinks.File` | `{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}` | If `WriteTo.File` does not compile, the package is missing - it is not a core method. Both sinks also accept a `restrictedToMinimumLevel` argument and an `ITextFormatter` overload for JSON output. ## The default minimum level Serilog has six levels, from most to least verbose: `Verbose`, `Debug`, `Information`, `Warning`, `Error`, `Fatal` (the `LogEventLevel` enum). A new `LoggerConfiguration` starts with its minimum at **`Information`**. So: 1. `Log.Debug("Queue depth {Depth}", depth)` is discarded unless you call `MinimumLevel.Debug()`. 2. `Log.Information`, `Warning`, `Error` and `Fatal` reach every sink. 3. A sink can be stricter than the logger (`restrictedToMinimumLevel: LogEventLevel.Warning`), but never more verbose. Note that Serilog's names differ from Microsoft.Extensions.Logging: Serilog says `Verbose` where `LogLevel` says `Trace`, and `Fatal` where `LogLevel` says `Critical`. ## Reading the default output The default output templates above are worth decoding, because interviewers sometimes show a log line and ask where it came from: - `{Timestamp:HH:mm:ss}` - the event time with a .NET format string; the file sink adds the date and the UTC offset (`zzz`). - `{Level:u3}` - the level as three upper-case letters: `VRB`, `DBG`, `INF`, `WRN`, `ERR`, `FTL`. - `{Message:lj}` - the rendered message; `l` writes strings without quotes and `j` renders embedded structured values as JSON. - `{NewLine}{Exception}` - a line break, then the exception and its stack trace when one was logged. You can change the layout with the `outputTemplate` argument, or switch a sink to machine-readable JSON by passing an `ITextFormatter` as its first argument. Either way the choice is per sink, so the console can stay human-friendly while the file is parsed by tools. ## Two things that surprise juniors - **`Log.Logger` starts silent.** Its initial value is `Logger.None`, a logger that drops everything. Calls made before you assign the configured logger produce no output and no exception. - **`CreateLogger()` works once per configuration.** A second call on the same `LoggerConfiguration` throws `InvalidOperationException` ("CreateLogger() was previously called and can only be called once"). Build a new configuration for a second logger. The logger also owns its sinks: it is `IDisposable` and `IAsyncDisposable`, and disposing it (for the static logger, via `Log.CloseAndFlushAsync()`) flushes and closes the file. ## How this shows up in an interview The screening version is "set up Serilog to log to console and a file". A good answer names the builder, the two sink packages, `CreateLogger()` and the `Information` default, and knows why a `Debug` line does not appear. Configuring the same pipeline from `appsettings.json`, level overrides per namespace, and flushing on shutdown are the natural next questions.

  • What happens if Log.Information is called before Log.Logger is assigned?
    Nothing visible. `Log.Logger` starts as `Logger.None`, a silent logger, so the event is discarded without an exception. That is why startup code assigns the configured logger first, before anything else can log.
  • Can you call CreateLogger() twice on the same LoggerConfiguration to get two loggers?
    No. The second call throws `InvalidOperationException` saying `CreateLogger()` can only be called once. Each logger needs its own `LoggerConfiguration`; if two parts of the app need different sinks, build two configurations or use a sub-logger with `WriteTo.Logger(...)`.
  • How would you send only warnings and above to the file while the console keeps Information?
    Pass `restrictedToMinimumLevel: LogEventLevel.Warning` to `WriteTo.File(...)`. The logger's minimum stays `Information`, so the console sees Information and above, and the file sink filters further. A sink restriction can only be stricter than the logger's level, never more verbose.

  • Serilog's default minimum level is Debug, so debug lines always show up
  • WriteTo.File is built into the core Serilog package
  • Logging before Log.Logger is assigned throws an exception
  • Serilog uses Trace and Critical as level names like LogLevel does
  • Calling CreateLogger twice on one configuration gives two independent loggers

Assumes Serilog 4.4 with Serilog.Sinks.Console 6.1 and Serilog.Sinks.File 7.0; the Information default and the sink split hold across Serilog 2 to 4.

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.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

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