Recipe 4.6 · Python
Logging in Console Apps and Windows Services
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
Scheduled console tools and Windows services fail where nobody is watching. Output goes to
Console.WriteLine, which disappears when Task Scheduler runs the job. Unhandled exceptions end
the process with a bare exit code. Each run's lines blur into the previous run's, so you cannot
tell which import processed which file.
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.
"""Console app main with print statements and swallowed failures
Source: ImproveCode, Chapter 4, Recipe 4.6 "Logging in Console Apps and Windows Services"
Section: The way it's often written
Book page: 94-95 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
print() replaces Console.WriteLine; Importer is a placeholder for the real job.
"""
from __future__ import annotations
from datetime import datetime
class Importer:
def run(self) -> None:
...
# Not this: no host, no structure, and failures vanish.
def main(args: list[str]) -> None:
print("Starting import " + str(datetime.now()))
try:
Importer().run()
except Exception as ex:
print(ex)
print("Done")
The improved recipe
Use the generic host so console tools get the same configuration and logging pipeline as web apps. Open a scope per run, time every run, and return a non-zero exit code on failure.
The worker opens a scope with a run ID and logs one start line and one end line per run:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Console/service host with structured logging and a background worker
Source: ImproveCode, Chapter 4, Recipe 4.6 "Logging in Console Apps and Windows Services"
Section: The improved recipe
Book page: 95-96 -- original C# listing
Converted from C# to Python.
asyncio replaces the .NET generic host (SIGINT/SIGTERM cancel the worker task);
stdlib logging with a JSON formatter and TimedRotatingFileHandler (daily, 30 backups)
replaces Serilog; ImportWorker is from p096_r4_6_hourly_import_background_worker.py.
"""
from __future__ import annotations
import asyncio
import json
import logging
import logging.handlers
import signal
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
log = logging.getLogger("host")
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
event: dict[str, Any] = {
"@t": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
"@m": record.getMessage(),
"@l": record.levelname,
"SourceContext": record.name,
}
if record.exc_info:
event["@x"] = self.formatException(record.exc_info)
return json.dumps(event, default=str)
def configure_logging() -> None:
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(logging.StreamHandler())
logs = Path(sys.argv[0]).resolve().parent / "logs"
logs.mkdir(exist_ok=True)
file_handler = logging.handlers.TimedRotatingFileHandler(
logs / "import.json", when="midnight", backupCount=30, encoding="utf-8")
file_handler.setFormatter(JsonFormatter())
root.addHandler(file_handler)
async def run_host(worker: Any) -> None:
task = asyncio.create_task(worker.execute())
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
try:
loop.add_signal_handler(sig, task.cancel)
except (NotImplementedError, RuntimeError):
pass # Windows: Ctrl+C raises KeyboardInterrupt instead
try:
await task
except asyncio.CancelledError:
pass
def main(worker: Any) -> int:
# Bootstrap: console logging until full configuration is in place.
logging.basicConfig(level=logging.INFO)
try:
configure_logging()
asyncio.run(run_host(worker))
return 0
except KeyboardInterrupt:
return 0
except Exception:
log.critical("Host terminated unexpectedly", exc_info=True)
return 1
finally:
logging.shutdown()
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Hourly import background worker with a per-run logging scope
Source: ImproveCode, Chapter 4, Recipe 4.6 "Logging in Console Apps and Windows Services"
Section: The improved recipe
Book page: 96-97 -- original C# listing
Converted from C# to Python.
An asyncio task loop replaces BackgroundService + PeriodicTimer; a LoggerAdapter
carrying RunId replaces BeginScope; time.perf_counter replaces Stopwatch;
asyncio.CancelledError replaces OperationCanceledException.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
class ImportWorker:
INTERVAL_SECONDS = 60 * 60 # one hour
def __init__(self, logger: logging.Logger | None = None) -> None:
self._logger = logger or logging.getLogger(__name__ + ".ImportWorker")
async def execute(self) -> None:
"""Runs once immediately, then every hour until the task is cancelled."""
while True:
await self._run_once()
await asyncio.sleep(self.INTERVAL_SECONDS)
async def _run_once(self) -> None:
run_id = uuid.uuid4().hex[:8]
logger = logging.LoggerAdapter(self._logger, {"RunId": run_id})
start = time.perf_counter()
logger.info("Import run started")
try:
rows = await self._import()
logger.info(
"Import run finished: %s rows in %s ms",
rows, int((time.perf_counter() - start) * 1000))
except asyncio.CancelledError:
logger.warning("Import run cancelled by shutdown")
raise
except Exception:
logger.error(
"Import run failed after %s ms",
int((time.perf_counter() - start) * 1000), exc_info=True)
@staticmethod
async def _import() -> int:
await asyncio.sleep(1) # real work here
return 0
How it works
Host.CreateApplicationBuilder gives a console app appsettings.json, environment variables,
dependency injection and ILogger with the same conventions as ASP.NET Core. The Serilog setup is
nearly identical to Recipe 4.2, so operations sees one log format across every host you deploy.
The file path is built from AppContext.BaseDirectory. Task Scheduler and the Service Control
Manager start processes with a working directory of C:\Windows\System32, which is where
relative log paths end up if you don't anchor them.
The RunId scope tags every line of one run, including lines from repositories and HTTP clients
deep in the call stack. Searching for one run ID shows exactly what that run did. The start and
finish lines with a row count and elapsed time are the two lines I read first every time: they
tell me whether the job ran, whether it finished and whether it did a normal amount of work.
The worker catches exceptions per run and keeps going, because one bad file should not stop
tomorrow's import. The outer try in Program.cs catches what escapes the host, writes it as
Fatal, flushes, and returns exit code 1 so Task Scheduler or a monitoring agent can alert.
Variations and pitfalls
- For a one-shot tool that runs and exits, skip the hosted service. Resolve your job class from
host.Services, run it, and return its result as the exit code. - To run the same code as a Windows service, add
Microsoft.Extensions.Hosting.WindowsServicesand callbuilder.Services.AddWindowsService(). Chapter 14 covers the service details. - The Windows Event Log is a poor primary log, but writing
Fatalevents there as well (with theSerilog.Sinks.EventLogpackage) means server monitoring tools notice a crashed service. - For a tiny utility without a host,
LoggerFactory.Create(b => b.AddSimpleConsole())gives youILoggerin two lines. Dispose the factory before exit so output is flushed. - Don't let a
BackgroundServiceexception escapeExecuteAsync. Since .NET 6, the default is to stop the host, which is usually right, but it should be your decision, made with a log line.