[Tech] Logging Patterns

Engineering guidelines part 3

Sakul Jaruthanaset
The S (mana)
2 min readSep 28, 2021

--

Photo by Mr Cup / Fabien Barral on Unsplash

Logging patterns

  1. Always specify an EventId. Include a numeric ID and a name. The name should be a PascalCasedCompoundWord (i.e. no spaces, and each "word" within the name starts with a capital letter).
  2. In production code, use “pre-compiled logging functions” (see below). Test code can use any kind of logging
  3. Prefer defining pre-compiled messages in a static class named Log that is a nested class within the class you are logging from. Messages that are used by multiple components can be defined in a shared class (but this is discouraged).
  4. Consider separating the Log nested class into a separate file by using partial classes. Name the additional file [OriginalClassName].Log.cs
  5. Never use string-interpolation ($"Foo {bar}") for log messages. Log message templates are designed so that structured logging systems can make individual parameters queryable and string-interpolation breaks this.
  6. Always use PascalCasedCompoundWords as template replacement tokens.

Pre-compiled Logging Functions

Production code should use “pre-compiled” logging functions. This means using LoggerMessage.Define to create a compiled function that can be used to perform logging.

For example, consider the following log statement:

The logging infrastructure has to parse the template ("You are having a bad problem and will not go to {Location} today") every time the log is written. A pre-compiled logging function allows you to compile the template once and get back a delegate that can be invoked to log the message without requiring the template be re-parsed.

For example:

If MyComponent is a large class, consider splitting the Log nested class into a separate file:

MyComponent.cs

MyComponent.Log.cs

Summary

  • 🤔????

References

--

--