IC Improve Code Recipes

Recipe 4.2 · C#

Structured Logging with Serilog

Problem

ILogger is only an abstraction. The built-in console and debug providers are fine for development, but production needs rolling files, a JSON format that a log tool can ingest, level overrides per namespace, and enrichment with properties such as the application name. You also want to capture failures that happen during startup, before dependency injection exists.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: a homegrown file writer with a lock and a date in the name.
public static class FileLogger
{
    private static readonly object Sync = new object();

    public static void Log(string text)
    {
        lock (Sync)
        {
            string path = @"C:\Logs\App_" +
                DateTime.Now.ToString("yyyyMMdd") + ".txt";
            File.AppendAllText(path, DateTime.Now + " " + text + "\r\n");
        }
    }
}

The improved recipe

Use Serilog (Serilog.AspNetCore, which brings the console, file and compact JSON packages) behind ILogger. Put level settings in configuration and sinks in code.

C#
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Formatting.Compact;

namespace ImproveCode.Logging;

public static class SerilogSetup
{
    public static WebApplicationBuilder AddAppSerilog(
        this WebApplicationBuilder builder)
    {
        string app = builder.Environment.ApplicationName;
        string env = builder.Environment.EnvironmentName;

        builder.Services.AddSerilog((services, log) => log
            .ReadFrom.Configuration(builder.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Application", app)
            .Enrich.WithProperty("Environment", env)
            .WriteTo.Console()
            .WriteTo.File(
                new CompactJsonFormatter(),
                "logs/app-.json",
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 14,
                fileSizeLimitBytes: 100_000_000,
                rollOnFileSizeLimit: true));

        return builder;
    }
}

Program.cs wraps startup so that a crash before the host is built still reaches a log:

C#
using System;
using ImproveCode.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();

try
{
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    builder.AddAppSerilog();

    WebApplication app = builder.Build();
    app.UseSerilogRequestLogging();
    app.MapGet("/", () => "OK");
    app.Run();
}
catch (Exception ex) when (ex is not HostAbortedException)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

The levels live in appsettings.json, so operations can change them per environment:

JSON
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore": "Warning",
        "System.Net.Http.HttpClient": "Warning"
      }
    }
  }
}

How it works

AddSerilog replaces the default providers, so every ILogger<T> in the app, including framework components, writes through Serilog. Your classes never reference Serilog directly. If you change logging libraries later, only this file changes.

The bootstrap logger is a minimal console logger that exists from the first line of Main. When the host builds, Serilog swaps in the full configuration. Without it, a bad connection string or a missing configuration key kills the process before any log is written, and the only evidence is an exit code in the Windows event log.

CompactJsonFormatter writes one JSON object per line, with the template, the rendered properties and the exception as separate fields. Seq, Elasticsearch, Splunk, Azure Monitor and most other tools ingest that format directly. Rolling by day plus a size cap plus a retention count keeps the disk from filling up, which is the second most common logging outage I see after "the log directory doesn't exist."

UseSerilogRequestLogging writes a single summary event per HTTP request (method, path, status code, elapsed time) instead of the several noisy events the framework writes by default. That is why the override sets Microsoft.AspNetCore to Warning.

Variations and pitfalls

  • Write the file sink to a path the app identity can write to. Under IIS that is not the site folder by default. A relative path resolves against the working directory, which differs between IIS, a Windows service and dotnet run.
  • For a central store, add a sink package such as Serilog.Sinks.Seq or the sink for your cloud log service, and keep the local file as a fallback.
  • Log.CloseAndFlush in finally matters. Sinks buffer, and a process that exits without flushing loses the last and most interesting events.
  • You can configure sinks in JSON with WriteTo arrays if you prefer. I keep sinks in code because type names and formatter strings in JSON fail silently when misspelled.
  • OpenTelemetry is the other modern path. If your organization has standardized on it, use the OpenTelemetry logging exporter behind the same ILogger calls. Nothing in your classes changes.

On .NET Framework

Serilog runs on .NET Framework 4.6.2 and later. Create the logger in Global.asax Application_Start (or Main for a service), assign it to Log.Logger, and call Log.CloseAndFlush() in Application_End. Classes can use Log.ForContext<T>() until you introduce dependency injection.