Logging in .NET with Serilog: Structured Logs Done Right

Set up logging in .NET with Serilog: message templates, ILogger, sinks, enrichers, appsettings configuration, request logging, and correlation ids.

Executive Summary: Logging in .NET with Serilog means treating log messages as data: message templates with named properties instead of pre-formatted strings, so “task {TaskId} completed” keeps its id searchable no matter which sink reads the events. Serilog plugs in behind the framework’s ILogger<T> facade, configured from appsettings.json, with sinks choosing where events go (console, rolling files, log servers) and enrichers stamping properties like correlation ids on every line.

The incident that shows why this topic deserves a whole page: a customer reports a failed checkout, the on-call engineer opens the log store, and searches for the order id. Nothing. The application logged the id inside interpolated sentences like Order 9a7f... failed for user Bob, and the store’s search cannot match “9a7f” when the field was never a field. The information was all there; it was just trapped inside prose.

Logging in .NET with Serilog is the combination of the framework’s logging abstraction (ILogger<T> and the logging abstractions every .NET library already writes to) with Serilog’s structured engine underneath: message templates, sinks, and enrichers. Serilog.net is the project’s home, and the ASP.NET Core logging fundamentals cover the facade this page builds on.

The examples assume .NET SDK 10.0 with C# 14 and continue the TaskApi. The pipeline that request logging middleware plugs into is the middleware guide’s territory.

Too many 3 a.m. log sessions taught me this: you do not write logs for the version of you that wrote the code. You write them for a tired person, months later, with one id and no context. Every choice below optimizes for that person.

Message templates: events, not strings

The core idea in structured logging is the message template: named placeholders become properties on the event, and the log store indexes them. One character separates the two worlds:

WRONG: interpolation destroys the data before it reaches the sink.

logger.LogInformation($"Task {task.Id} completed");   // "Task 9a7f... completed"
// the id is now buried in prose; no field, no filter

RIGHT: the template preserves the id as a queryable property.

logger.LogInformation("Task {TaskId} completed", task.Id);
// message: "Task 9a7f6e... completed"
// property: TaskId = "9a7f6e..."   <- filterable, groupable, countable

The rule is mechanical and worth automating in review: interpolation ($"") in a log call is a defect. The template stays constant, the properties carry the variables, and downstream queries like TaskId = "9a7f..." find every line about that task across every environment.

The six levels and what each one is for

Level Means Typical content Volume policy
Trace Developer internals Method entry and exit Never in production
Debug Diagnostic detail Values, decisions inside branches Development only
Information The service’s story Requests, commands, jobs started and finished Default production level
Warning Handled trouble Retries, fallbacks, slow queries On, reviewed weekly
Error Failed operation Exceptions with context On, paged and alerted
Critical System-level failure Datastore unreachable, startup failure On, always wakes someone

The most common misuse is level inflation: logging routine flow at Error, so alerting learns to ignore errors. The second most common is silence. A catch block that swallows an exception without a log line is a decision to be surprised later.

ILogger<T>: write to the facade, let Serilog receive

Application code logs through the framework’s ILogger<T>, injected by the container, and never references Serilog directly. The category (T, usually the logging class) tags every event with its source, which is what level overrides filter on. Serilog’s job is to sit behind that facade as the provider:

public sealed class TaskService(ILogger<TaskService> logger)
{
    public async Task CompleteAsync(Guid taskId, CancellationToken ct)
    {
        logger.LogInformation("Completing task {TaskId}", taskId);

        // ... work ...

        logger.LogInformation("Task {TaskId} completed", taskId);
    }
}

This split is why logging stays swappable: services depend on ILogger<T> from the base libraries, and Serilog (or any provider) is a deployment detail behind it.

Serilog setup, configured from appsettings

One package wires Serilog behind the facade, and one line moves its configuration into appsettings.json:

dotnet add package Serilog.AspNetCore
builder.Host.UseSerilog((context, configuration) =>
    configuration.ReadFrom.Configuration(context.Configuration));
// appsettings.json
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "logs/taskapi-.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 14
        }
      }
    ]
  }
}

Two settings in that file carry more value than they appear to. The overrides quiet the framework’s own chatty categories (ASP.NET Core logs a surprising number of Information lines per request) while leaving the EF Core command category at Information, which is exactly how the query efficiency guide watches the SQL a request sends. Configuration in appsettings means environments differ (console-only in containers, files on a VM) without code changes.

Sinks: where events go

A sink is a destination Serilog writes events to. The value is that they compose: the same events flow to console and file simultaneously. Adding a third destination is a configuration entry:

Sink Use it for Notes
Console Containers, development The only sink most container deployments need; the platform collects stdout
File (rolling) VMs, on-premises Daily rolling with retainedFileCountLimit keeps disk bounded
Seq, Elasticsearch, and similar log servers Teams, search, dashboards Properties become first-class filters and charts
OpenTelemetry Modern observability stacks Routes events, metrics, and traces through one pipeline

In containers the console sink is the sensible default: the platform (Docker, Kubernetes) owns collection and rotation. Writing files inside a container usually means logs that vanish with the pod. The Kubernetes guide in this series shows how the same stdout becomes platform logs on the cluster side.

Enrichers: properties on every line

An enricher stamps properties onto events as they flow through the pipeline: machine name, environment name, or, most usefully, the correlation id. The request trace identifier is the same one the error handling guide writes into Problem Details, which makes logs and error responses answer to the same key:

builder.Host.UseSerilog((context, configuration) =>
    configuration
        .ReadFrom.Configuration(context.Configuration)
        .Enrich.FromLogContext());
// per-request: one id, every log line, matching the error response
app.Use((context, next) =>
{
    LogContext.PushProperty("CorrelationId", context.TraceIdentifier);
    return next(context);
});

Now every event inside the request, from controller to repository, carries CorrelationId, and the support ticket quoting the id from a Problem Details response finds the whole request’s story. That closes the loop the error handling guide starts: response carries the id, log carries the id, incident takes minutes.

Request logging: one line per request

Serilog.AspNetCore ships a middleware that replaces the scattered per-request framework logs with one structured, completion-time event:

app.UseSerilogRequestLogging();   // early in the pipeline, after exception handling

The event includes method, path, status code, elapsed time, and it respects the middleware placement rules from the pipeline guide. Register it near the top, after the exception handler, so it measures the full request and catches failures too. One line per request at Information level is the backbone of an API’s log story: enough to answer “what happened at 14:03” without opening a query tool, cheap enough to leave on forever.

No secrets or personal data in logs

The rule that outranks every other advice on this page: logs are read by people and systems you cannot enumerate, stored longer than your data retention for databases, and searchable. Treat them as the most widely distributed artifact the service produces:

  • Never log: passwords, tokens, connection strings, full card numbers, session cookies, secrets from configuration.
  • Prefer identifiers over contents: log the user id, not the user’s email or name; log the order id and a status, not the order object (payloads also make log lines enormous).
  • Mask at the edge: when a value must appear, mask it (****4321) or log only a prefix and length.
  • Log levels are not access control: a Trace line in production is a shipped line. Debug-level secrets are still secrets.

How real systems do this

  • One id connects everything. The correlation id appears in request logs, error responses, and exceptions, so a ticket with an id resolves to the exact request, its SQL, and its failure in one query.
  • Levels are a policy, not a mood. The team agrees on the level table above, writes it in the handbook, and reviews new log calls the way it reviews naming: information for the story, warning for handled trouble, error only when a human should know.
  • Dashboards come from properties. Request-duration charts, error-rate alerts, and slow-query lists are built from the structured fields, not from parsing text, which is the whole payoff of the template discipline.

An incident I remember well lived in exactly the interpolation trap this guide opens with: a checkout failure logged with string interpolation, one missing field, and forty minutes of an engineer grepping sentence fragments while the customer waited. The same code with message templates would have been a two-second filter on the order id. Afterward, “no $ in log statements” joined the review checklist, and search-the-id became the first move instead of the last resort. What I took from it: structured logging is not a nice-to-have for big companies. It is the difference between finding the line and reading the disk.

Decision framework: what to log and where

  1. Would a support ticket need this line? Log it at Information with the ids a ticket would quote. If it only matters while stepping through the code, it is Debug.
  2. Did something fail? Error with the exception and the operation’s ids. If you rethrow, the boundary’s handler logs it once (the error handling guide owns that rule), so this layer does not double-log.
  3. Is the event inside a loop over thousands of items? Aggregate. One summary line with counts and duration beats a thousand lines nobody reads.
  4. Which sink does this environment need? Containers: console. VMs: rolling file. Team search: a log server. Configure per environment in appsettings, not per code change.
  5. Does every event carry the correlation id? If not, add the enricher before shipping. A log store without an id is a story without a protagonist.

When NOT to log

  • Tight loops and hot paths. Logging per item at Information level in a million-row batch buries the useful lines and costs real money in volume. Log the summary.
  • When you rethrow the same exception. Catch-log-rethrow writes every incident three times; log at the boundary that handles it, once.
  • Framework plumbing already covered. ASP.NET Core and EF Core log their own categories. Add configuration, not code, when you want their events.
  • Anything that fails the secrets rule. No level, no sink, and no environment makes a token safe to write down.

Common mistakes

  • Interpolation in log calls. $"..." turns properties into prose and defeats every downstream query; templates keep the data.
  • Logging whole entities and payloads. It leaks personal data, bloats volume, and couples log retention to your domain shape. Log ids and statuses.
  • Error level for normal flow. Alerts trained on noise are alerts nobody reads; reserve Error for things a human should see.
  • Swallowing exceptions silently. A catch without a log is a decision to investigate blind later; at minimum log the exception with context.
  • Secrets at “temporary” debug level. Debug logs ship to the same stores. If a value is secret, it never appears at any level.
  • No correlation id. Without it, every investigation starts with timestamps and luck. One enricher makes every line of a request findable.

For the architecture around the logger, see structured, centralized, and searchable logging. The same habits apply in Python logging and in Java with SLF4J and Logback.

Key takeaways

  • Message templates with named properties are the whole point: logger.LogInformation("Task {TaskId} completed", task.Id), never interpolation.
  • Write code against ILogger<T>; Serilog plugs in behind it with UseSerilog and ReadFrom.Configuration for appsettings-driven setup.
  • Levels are policy: Information for the story, Warning for handled trouble, Error for failures a human should see. Quiet the framework’s noisy categories with overrides.
  • Sinks compose: console for containers, rolling files for VMs, a log server when a team needs search. Configuration, not code, decides per environment.
  • Enrichers stamp the correlation id on every event, matching the trace id in Problem Details, so tickets resolve in one query.
  • UseSerilogRequestLogging() gives one structured line per request with method, path, status, and duration.
  • Logs are the widest-read artifact: no secrets, no personal data, ids over contents, always.

FAQ

What is structured logging in .NET?

Logging events as data instead of pre-formatted text: the message template names its placeholders, and each logged call stores the values as queryable properties. A log server can then filter for TaskId equals a specific value, instead of searching for a sentence fragment inside interpolated strings.

What is the difference between ILogger and Serilog?

ILogger<T> is the logging facade from the base class libraries that application code depends on. Serilog is a provider that plugs in behind it with message templates, sinks, and enrichers. Code written against ILogger stays provider-neutral, and swapping or configuring the engine is a startup and configuration concern.

How do I configure Serilog from appsettings.json?

Add the Serilog.AspNetCore package, call builder.Host.UseSerilog with ReadFrom.Configuration passing the builder’s configuration. Then describe minimum levels, overrides, and the WriteTo sinks in the Serilog section of appsettings.json. Environments vary the file, not the code.

What is a sink in Serilog?

A destination for log events: console, rolling files, a log server such as Seq or Elasticsearch, or an OpenTelemetry pipeline. Sinks compose, so one configuration can write to several at once, and adding or changing a destination is configuration rather than a code change.

What does UseSerilogRequestLogging do?

It registers middleware that emits one structured event per HTTP request when it completes, with method, path, status code, and elapsed time. Register it near the top of the pipeline, after the exception handler. This means it captures failures and measures the full request instead of replacing the framework’s scattered per-request logging.

Log events, not sentences

Structured logging is a discipline with compounding returns. Every template you write correctly makes the next incident shorter, and the correlation id turns a support ticket into a query. Write to the facade, configure the engine per environment, respect the levels, keep secrets out, and let the sinks and dashboards do the reading. Next in the operations track: caching in ASP.NET Core, and every guide in the series lives on the .NET series index. The rule of thumb: log the event with its ids, and the sentence will write itself when someone needs to read it.

Last updated on 22 November 2026

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *