Ariel Shaqed (Scolnicov)
08/07/2023, 5:51 AMLogger.WithContext
to incorporate context fields into an existing Logger .
b. Use`logging.FromContext` to create a new Logger with context fields.
c. I've renamed logging.Default
to the slightly harder to type and less pleasant to read logging.ContextUnavailable
.
tl:
We use context fields, specifically the request ID, to connect the different logs emitted while processing a single request. Without these it can be very difficult to understand the flow of a single request. All you have to do is use logging.FromContext
to create your Logger or Logger.WithContext
to mix existing context with an existing Logger. The only reason not to use context on your Logger is in tests, during startup, or during shutdown. Even in these cases, you often have a context simply to be able to perform other operations. The context for a req http.Request
is req.Context()
, and middleware at the start of the chain puts the request ID onto it. In almost every func that performs an operation there will be a ctx context.Context
that holds a context. Use it!
Over time we drifted away from this, and many of our logs lost their request IDs. I've just pulled treeverse/lakeFS#6312. It fixes all the uses that I could find that were missing a context. I also took the liberty of renaming logging.Default
to logging.ContextUnavailable
. This should encourage you to use a context - 2 fewer characters to type and a happier ariels
! Please call out its uses when reviewing code.
Thanks for adding context to all our debugging sessions!