Recipe 4.5 · Python
Replacing the Homegrown LogHelper
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
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
The code base has a static LogHelper with 1,500 call sites. It writes to a text file, sometimes
to a database table, and catches every exception it hits. You want ILogger everywhere, but you
cannot change 1,500 lines in one release, and many of the callers are static utility methods with
no constructor to inject into.
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.
"""The classic homegrown LogHelper class
Source: ImproveCode, Chapter 4, Recipe 4.5 "Replacing the Homegrown LogHelper"
Section: The way it's often written
Book page: 91-92 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
os.environ["LogPath"] stands in for ConfigurationManager.AppSettings["LogPath"];
the bare `except: pass` mirrors the C# empty catch.
"""
from __future__ import annotations
import os
from datetime import datetime
# Not this: the classic LogHelper.
class LogHelper:
@staticmethod
def error(msg: str, ex: BaseException) -> None:
try:
path = os.environ.get("LogPath")
with open(path, "a", encoding="utf-8") as f: # type: ignore[arg-type]
f.write(str(datetime.now()) + " ERROR " + msg +
" " + str(ex) + os.linesep)
except: # noqa: E722
pass
@staticmethod
def info(msg: str) -> None:
... # same again
The improved recipe
Keep the class name and the method signatures, and turn the body into a thin adapter over
ILoggerFactory. Mark the methods obsolete so the compiler lists every call site you still have
to migrate.
At startup, as a usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Transitional LogHelper adapter that forwards to the logging framework
Source: ImproveCode, Chapter 4, Recipe 4.5 "Replacing the Homegrown LogHelper"
Section: The improved recipe
Book page: 92-93 -- original C# listing
Converted from C# to Python.
logging.getLogger replaces ILoggerFactory.CreateLogger; [CallerFilePath]/[CallerMemberName]
are recovered with inspect stack frames; [Obsolete] becomes a DeprecationWarning;
a NullHandler-only logger plays the role of NullLoggerFactory until initialize() is called.
"""
from __future__ import annotations
import inspect
import logging
import warnings
from pathlib import Path
from typing import Callable
class LogHelper:
"""Transitional adapter. Existing call sites keep working while
they move to module-level loggers (logging.getLogger(__name__))."""
_MIGRATE = "Use logging.getLogger(__name__) instead of calling LogHelper."
_factory: Callable[[str], logging.Logger] | None = None
@classmethod
def initialize(cls, factory: Callable[[str], logging.Logger]) -> None:
if factory is None:
raise ValueError("factory must not be None")
cls._factory = factory
@classmethod
def info(cls, message: str) -> None:
file, member = cls._caller()
cls._for(file).info("%s (%s)", message, member)
@classmethod
def warn(cls, message: str) -> None:
file, member = cls._caller()
cls._for(file).warning("%s (%s)", message, member)
@classmethod
def error(cls, message: str, ex: BaseException | None = None) -> None:
file, member = cls._caller()
cls._for(file).error("%s (%s)", message, member, exc_info=ex)
@classmethod
def _caller(cls) -> tuple[str, str]:
warnings.warn(cls._MIGRATE, DeprecationWarning, stacklevel=3)
frame = inspect.stack()[2]
return frame.filename, frame.function
# Uses the calling file name as the category, so filtering
# by module still works for legacy callers.
@classmethod
def _for(cls, file: str) -> logging.Logger:
category = "Legacy" if not file else "Legacy." + Path(file).stem
if cls._factory is None:
null_logger = logging.getLogger("_null." + category)
null_logger.propagate = False
if not null_logger.handlers:
null_logger.addHandler(logging.NullHandler())
return null_logger
return cls._factory(category)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Initializing the LogHelper adapter at application startup
Source: ImproveCode, Chapter 4, Recipe 4.5 "Replacing the Homegrown LogHelper"
Section: The improved recipe
Book page: 93 -- original C# listing
Converted from C# to Python.
logging.getLogger is passed as the logger factory (ILoggerFactory from DI in C#);
LogHelper is the adapter from p092_r4_5_loghelper_transitional_adapter.py.
"""
from __future__ import annotations
import logging
from typing import Any
def startup(log_helper: Any) -> None:
# After logging is configured (equivalent of builder.Build()):
log_helper.initialize(logging.getLogger)
How it works
Every old call now flows into the same pipeline as new code: Serilog, the correlation scope, level filtering, the JSON file. You get the benefits on day one without editing a single caller.
The compiler fills in [CallerFilePath] and [CallerMemberName] at each call site, so a call
from InvoiceService.cs logs under the category Legacy.InvoiceService with the method name
attached. The old text file never told you that.
[Obsolete] turns every remaining call into a build warning. The warning count becomes your
migration progress bar, and new code that reaches for LogHelper is flagged in review.
The migration I use:
- Replace the body of the existing
LogHelperwith the adapter, keeping public signatures. - Call
Initializeat startup in every host (web app, service, console tools). - Delete the old log file writer and any
catch { }inside the logging code. - Move classes to injected
ILogger<T>when you touch them for other reasons. - When the warning count reaches zero, delete
LogHelper.
Variations and pitfalls
- If the old helper had overloads such as
Error(Exception ex)orDebug(string), keep them. The point is that no caller has to change yet. - Before
Initializeruns, the null factory drops messages. If you have static constructors that log, either initialize earlier or accept that those few lines go nowhere. - If the old helper wrote to a database table that a support screen reads, keep that table as a separate sink (Serilog has an MS SQL Server sink) until the screen is retired. Don't break the support team's workflow during a refactor.
- Resist adding new features to the adapter. It exists to be deleted.
On .NET Framework
The same adapter works on .NET Framework 4.6.2 and later with the
Microsoft.Extensions.Logging package. Build a factory in Application_Start with
LoggerFactory.Create(b => b.AddSerilog()) (from Serilog.Extensions.Logging) and pass it to
Initialize.