IC Improve Code Recipes

Recipe 4.1 · Python

ILogger and Message Templates

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

Log lines are built with string concatenation or interpolation. They read fine to a human, but a log search tool sees only text. You cannot ask "show me every failure for order 48213" or "how many payments over $10,000 failed today" without regular expressions and luck.

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 Logging with values baked into the message text (p080_r4_1_string_concatenated_logging_before.py)
"""Logging with values baked into the message text

Source: ImproveCode, Chapter 4, Recipe 4.1 "ILogger and Message Templates"
Section: The way it's often written
Book page: 80  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
A homegrown Logger.write stands in for the C# static Logger.Write; string
concatenation/f-strings bake values into text, and every exception is swallowed.
"""

from __future__ import annotations

from typing import Any


class Logger:
    """Stand-in for the homegrown static logger the C# calls."""

    @staticmethod
    def write(text: str) -> None:
        print(text)


class OrderService:
    def __init__(self, gateway: Any) -> None:
        self._gateway = gateway

    # Not this: the values are baked into the text.
    def process(self, order: Any) -> None:
        Logger.write("Processing order " + str(order.id) + " for " +
                     f"${order.total:,.2f}")
        try:
            self._gateway.charge(order)
        except Exception as ex:
            Logger.write(f"Error processing order {order.id}: {ex}")

The improved recipe

Inject ILogger<T> and pass values as arguments to a message template. For hot paths and for messages you want to catalog, use the LoggerMessage source generator.

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

Python Order processing with structured log messages and event IDs (p080_r4_1_structured_order_logging_templates.py)
"""Order processing with structured log messages and event IDs

Source: ImproveCode, Chapter 4, Recipe 4.1 "ILogger and Message Templates"
Section: The improved recipe
Book page: 80-81  -- original C# listing
Converted from C# to Python.
logging module replaces ILogger<T>; the [LoggerMessage] source-generated methods
become small helper functions that log a %-style template and pass the values as
structured fields via `extra` (event_id plus named properties).
"""

from __future__ import annotations

import asyncio
import logging
from dataclasses import dataclass
from decimal import Decimal
from typing import Protocol


@dataclass(frozen=True)
class Order:
    id: int
    customer_id: str
    total: Decimal


class PaymentGateway(Protocol):
    async def charge(self, order: Order) -> None: ...


class OrderLog:
    """Equivalent of the C# partial class with [LoggerMessage] methods."""

    @staticmethod
    def processing_order(
        logger: logging.Logger, order_id: int, customer_id: str, total: Decimal
    ) -> None:
        logger.info(
            "Processing order %s for customer %s, total %s",
            order_id, customer_id, total,
            extra={"event_id": 1001, "OrderId": order_id,
                   "CustomerId": customer_id, "Total": str(total)},
        )

    @staticmethod
    def payment_failed(
        logger: logging.Logger, ex: BaseException, order_id: int, total: Decimal
    ) -> None:
        logger.error(
            "Payment failed for order %s, total %s",
            order_id, total,
            exc_info=ex,
            extra={"event_id": 1002, "OrderId": order_id, "Total": str(total)},
        )


class OrderProcessor:
    def __init__(self, gateway: PaymentGateway, logger: logging.Logger | None = None) -> None:
        self._gateway = gateway
        self._logger = logger or logging.getLogger(__name__ + ".OrderProcessor")

    async def process(self, order: Order) -> bool:
        """Cancellation is carried by asyncio task cancellation (no CancellationToken)."""
        OrderLog.processing_order(self._logger, order.id, order.customer_id, order.total)

        try:
            await self._gateway.charge(order)
            self._logger.info(
                "Order %s charged successfully", order.id,
                extra={"OrderId": order.id},
            )
            return True
        except (TimeoutError, asyncio.TimeoutError) as ex:
            OrderLog.payment_failed(self._logger, ex, order.id, order.total)
            return False

How it works

A message template looks like a format string, but the names in braces are property names, not positions. When the provider supports structured logging, {OrderId} becomes a field named OrderId with the value 48213, stored alongside the rendered text. Your log store can then filter, group and chart on it. The rendered message still reads naturally for humans.

The exception goes in the first parameter, not into the message. Every provider knows how to write the full exception, including the stack trace and inner exceptions. ex.Message alone throws away the most useful part.

ILogger<OrderProcessor> sets the category to the full type name. That gives you per-namespace filtering in configuration (for example, Warning for Microsoft.AspNetCore, Debug for your own data layer while you chase a bug) without touching code.

The [LoggerMessage] attribute tells the compiler to generate the method body. The generated code checks IsEnabled before doing any work, avoids boxing the value types, and parses the template once at compile time. It also gives each message a stable EventId, which operations teams love: an alert rule on event 1002 survives any rewording of the text.

Variations and pitfalls

  • Never interpolate into a template: LogInformation($"Order {id}") compiles and runs, but it produces a new template for every value and loses the property. The CA2254 analyzer warns about this; turn it on.
  • Keep property names consistent across the code base. If one class logs {OrderId} and another logs {OrderNo}, your query needs both. A short list of standard names in the team wiki pays off quickly.
  • Pick levels deliberately. Information is for events an operator wants to see in a normal day (job started, job finished, order placed). Debug is for developers. Warning means something unexpected happened but the app recovered. Error means an operation failed. Critical means the process or a whole feature is down.
  • Don't guard every call with if (logger.IsEnabled(...)). The extension methods already check. Guard only when computing an argument is expensive.
  • Format specifiers work: {Total:C} renders as currency in the text while the property keeps the raw number.