I spent some time reading through the docs of the logging
library in Python. It’s a bit of a pain to use.
Someone on Bluesky pointed me to structlog
.
The one thing that convinced me to try it out was the context manager.
You can do something like this:
This is sick for web applications.
You can bind user parameters to the logger in the middleware and be done with it.
When you have already written your log messages, it will take you a while to migrate to structlog
.
It is designed to have minimal event names instead of verbose messages.
You add variables to the log messages and don’t insert them into the message string.
This makes it easier to render them in different formats.
You use the configuration to set the format
You can set the format of the log messages in the configuration.
This renders the log messages as JSON.
But you can also use the ConsoleRenderer
to render the log messages as text (in colors ;)).
The base configuration I went with in my project is this:
CallsiteParameterAdder
adds the file name, function name, and line number to the log message.TimeStamper
adds the timestamp to the log message.StackInfoRenderer
adds the stack trace to the log message.ExceptionPrettyPrinter
adds the exception to the log message.UnicodeDecoder
decodes the log message to Unicode.ConsoleRenderer
renders the log message to the console.
Good logging is like having a clear conversation with you in a few years when you have forgotten what you did.