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?
answer
- fluent builder ending in CreateLogger()
- sinks ship as separate NuGet packages
- WriteTo.Console() and WriteTo.File(path, ...)
- rollingInterval: RollingInterval.Day
- default minimum level: Information
basics
~10 sChain 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 sA 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 linesdotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.Filego deeper
Write the builder from memory: LoggerConfiguration, WriteTo.Console, WriteTo.File with RollingInterval.Day, CreateLogger, and assignment to Log.Logger. Name the two sink packages.
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.
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.
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.