IC Improve Code Recipes

Recipe 4.2 · Python

Structured Logging with Serilog

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Homegrown file logger with a lock and a date in the file name (p082_r4_2_homegrown_locked_file_logger_before.py)
"""Homegrown file logger with a lock and a date in the file name

Source: ImproveCode, Chapter 4, Recipe 4.2 "Structured Logging with Serilog"
Section: The way it's often written
Book page: 82  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
threading.Lock replaces the C# lock statement; the hard-coded Windows path is kept.
"""

from __future__ import annotations

import threading
from datetime import datetime


# Not this: a homegrown file writer with a lock and a date in the name.
class FileLogger:
    _sync = threading.Lock()

    @staticmethod
    def log(text: str) -> None:
        with FileLogger._sync:
            path = r"C:\Logs\App_" + datetime.now().strftime("%Y%m%d") + ".txt"
            with open(path, "a", encoding="utf-8", newline="") as f:
                f.write(str(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.

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

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"
      }
    }
  }
}

Requirements: Python 3.12+. Install: pip install fastapi uvicorn

Python Application entry point with bootstrap logging and request logging (p083_r4_2_fastapi_startup_with_logging.py)
"""Application entry point with bootstrap logging and request logging

Source: ImproveCode, Chapter 4, Recipe 4.2 "Structured Logging with Serilog"
Section: The improved recipe
Book page: 83-84  -- original C# listing
Converted from C# to Python.
FastAPI + uvicorn replace the ASP.NET Core minimal host; an HTTP middleware stands in
for UseSerilogRequestLogging; logging.shutdown() replaces Log.CloseAndFlush().
add_app_logging is the function from p083_r4_2_structured_json_logging_setup.py.
"""

from __future__ import annotations

import logging
import time
from typing import Awaitable, Callable

import uvicorn
from fastapi import FastAPI, Request, Response

log = logging.getLogger("app")


def add_app_logging(app_name: str) -> None:
    """See p083_r4_2_structured_json_logging_setup.py (Recipe 4.2)."""
    logging.basicConfig(level=logging.INFO)


def main() -> None:
    # Bootstrap logger: console only, until full configuration is in place.
    logging.basicConfig(level=logging.INFO)

    try:
        add_app_logging("app")

        app = FastAPI()

        @app.middleware("http")
        async def request_logging(
            request: Request, call_next: Callable[[Request], Awaitable[Response]]
        ) -> Response:
            start = time.perf_counter()
            response = await call_next(request)
            elapsed_ms = (time.perf_counter() - start) * 1000
            log.info(
                "HTTP %s %s responded %s in %.4f ms",
                request.method, request.url.path, response.status_code, elapsed_ms,
            )
            return response

        @app.get("/")
        def root() -> str:
            return "OK"

        uvicorn.run(app)
    except Exception:
        log.critical("Application terminated unexpectedly", exc_info=True)
    finally:
        logging.shutdown()


if __name__ == "__main__":
    main()

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Configure structured logging: console plus rolling compact-JSON files (p083_r4_2_structured_json_logging_setup.py)
"""Configure structured logging: console plus rolling compact-JSON files

Source: ImproveCode, Chapter 4, Recipe 4.2 "Structured Logging with Serilog"
Section: The improved recipe
Book page: 83  -- original C# listing
Converted from C# to Python.
The stdlib logging module replaces Serilog: a JSON formatter stands in for
CompactJsonFormatter, TimedRotatingFileHandler (daily, 14 backups) for the rolling
file sink, and a Filter adds the Application/Environment enrichment properties.
Python's stdlib cannot roll on both time and size at once, so the 100 MB size cap is noted only.
"""

from __future__ import annotations

import json
import logging
import logging.handlers
import os
from datetime import datetime, timezone
from pathlib import Path

_RESERVED = set(vars(logging.makeLogRecord({})).keys()) | {"message", "asctime"}


class CompactJsonFormatter(logging.Formatter):
    """One JSON object per line, similar to Serilog's compact JSON format."""

    def format(self, record: logging.LogRecord) -> str:
        event: dict[str, object] = {
            "@t": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
            "@mt": record.msg if isinstance(record.msg, str) else str(record.msg),
            "@m": record.getMessage(),
            "@l": record.levelname,
            "SourceContext": record.name,
        }
        if record.exc_info:
            event["@x"] = self.formatException(record.exc_info)
        for key, value in vars(record).items():
            if key not in _RESERVED and not key.startswith("_"):
                event[key] = value
        return json.dumps(event, default=str)


class EnrichFilter(logging.Filter):
    """Equivalent of Enrich.WithProperty(...)."""

    def __init__(self, **properties: str) -> None:
        super().__init__()
        self._properties = properties

    def filter(self, record: logging.LogRecord) -> bool:
        for key, value in self._properties.items():
            setattr(record, key, value)
        return True


def add_app_logging(app_name: str, env_name: str | None = None) -> None:
    """Equivalent of builder.AddAppSerilog(); level can come from LOG_LEVEL."""
    env = env_name or os.environ.get("APP_ENVIRONMENT", "Production")
    enrich = EnrichFilter(Application=app_name, Environment=env)

    root = logging.getLogger()
    root.setLevel(os.environ.get("LOG_LEVEL", "INFO"))

    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter(
        "[%(asctime)s %(levelname)s] %(name)s: %(message)s"))
    console.addFilter(enrich)

    Path("logs").mkdir(exist_ok=True)
    file_handler = logging.handlers.TimedRotatingFileHandler(
        "logs/app.json",
        when="midnight",       # rollingInterval: RollingInterval.Day
        backupCount=14,        # retainedFileCountLimit: 14
        encoding="utf-8",
    )
    # fileSizeLimitBytes: 100_000_000 / rollOnFileSizeLimit have no direct
    # stdlib equivalent when combined with time-based rolling.
    file_handler.setFormatter(CompactJsonFormatter())
    file_handler.addFilter(enrich)

    root.addHandler(console)
    root.addHandler(file_handler)

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.