log4cats icon indicating copy to clipboard operation
log4cats copied to clipboard

Way to copy a logger's context onto a logger with a different name

Open timbertson opened this issue 1 year ago • 2 comments

I have two loggers, let's say they're named rpc and eval.

I want to handoff processing from the rpc to eval module, but my rpc logger has request info in its context, which I want to include when I make logging calls from the eval logger.

#238 is one solution, I could copy my rpc logger and also name it eval. Alternatively, if there was a way to extract the context from a logger I could either pass that around detached from the original logger, or write a function which adopted the context from a passed-in logger.

timbertson avatar Jul 06 '24 01:07 timbertson

Another way to achieve this might be to have an implicit context object, which each log call accepts, and includes that context with the log statement. That way you pass around the context, and pair it with your module / class-level logger.

That would save you from having to build a fresh logger each time execution changes hands between modules. But maybe the ergonomics get awkward, as there's now 2 (or 3?) ways to inject context.

timbertson avatar Jul 06 '24 01:07 timbertson

As of v2.7.0 this is currently possible to do by adding the context in the LoggerFactory rather than StructuredLogger (See: LoggerFactory#addContext)

There's also Issue #461 about using Local for context and the closely aligned PR #900, but those aren't in yet.

morgen-peschke avatar Mar 19 '25 18:03 morgen-peschke