Chapter 4
Logging That Helps at 2 A.M.
The phone rings at 2 A.M. because the nightly billing job failed. You open the log file and find
four thousand lines that say Error occurred and nothing else. No order number, no user, no stack
trace, no hint of which of the forty concurrent requests the line belonged to. The log exists, it
grew to 3 GB, and it is useless. I have been on that call more times than I would like, and the
cause was almost never a missing log statement. It was log statements written for the person who
wrote the code that afternoon, not for the person reading them in the middle of the night.
Every shop builds logging early, and almost every shop builds it by hand. In my archive, 29 of the
35 engagements with C# code contain hand-written logging classes, 11,946 of them in total, and a
class named LogHelper appears in 231 copies. Only 13 of those 35 engagements used a logging
library such as log4net, NLog or Serilog at all, and only about 1,496 files reference one. Most of
the homegrown classes do the same thing: open a text file, append a line with a timestamp, close
the file, and swallow any exception so that logging never breaks the app. Some are clever. Very
few are searchable.
Modern .NET gives you a logging abstraction in the box (ILogger), a convention for structured
messages, and a healthy ecosystem of sinks. This chapter shows how to use them so that the log
answers three questions fast: what happened, to which record, and as part of which request. It
also covers what you must never write to a log, how to retire a homegrown LogHelper without a
big-bang rewrite, and how to log properly from console tools and Windows services.
Recipes
- 4.1ILogger and Message TemplatesLog 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…
- 4.2Structured Logging with SerilogILogger is only an abstraction. The built-in console and debug providers are fine for development, but production needs rolling files, a JSON format…
- 4.3Correlation IDs Across Requests and ServicesUnder load, log lines from many requests interleave. A failure in the payment service shows up seconds after the web front end logged "checkout…
- 4.4What to Log and What Never to LogLogs get two kinds of wrong. Some say too little: "Error" with no context. Others say far too much: full request bodies with passwords, card numbers…
- 4.5Replacing the Homegrown LogHelperThe 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…
- 4.6Logging in Console Apps and Windows ServicesScheduled console tools and Windows services fail where nobody is watching. Output goes to Console.WriteLine, which disappears when Task Scheduler…
Chapter checklist
- Search for
LogHelper,File.AppendAllTextandConsole.WriteLinein your production code and list every homegrown logging path. - Replace string concatenation and interpolation in log calls with message templates, and turn on the CA2254 analyzer.
- Configure Serilog (or OpenTelemetry) once per host, with a bootstrap logger and
CloseAndFlushinfinally. - Add correlation ID middleware and show the ID on error pages and API error responses.
- Review log calls for passwords, tokens, connection strings and whole request objects, and mask or remove them.
- Wrap the old
LogHelperin an obsolete adapter and track the warning count down to zero. - Give every scheduled job a run ID scope, a start line, a finish line with counts and elapsed time, and a non-zero exit code on failure.