qos-ch / slf4j

Simple Logging Facade for Java
http://www.slf4j.org
MIT License
2.32k stars 980 forks source link

Pass key-value properties into events in slf4j-reload4j. #394

Open josephw opened 7 months ago

josephw commented 7 months ago

I'm aiming to migrate an existing codebase off Log4j as a logging framework. Logging is through SLF4J, but there's also extensive direct use of Log4j's org.apache.log4j.MDC to pass values (other than Strings) through to a Layout that produces structured logging output.

An incremental migration would be significantly easier if I were able to adopt SLF4J's new fluent API without having to simultaneously change the backend logging framework.

This PR makes exactly that change: the key-value properties from the fluent API are merged into the snapshot of the MDC, leaving the existing logging backend with exactly the same data, while the logging calls lose their direct dependency on Log4j.

It's not clear to me whether this approach was considered and rejected, because it conflates the two different types of property, or whether it's suitable as a general purpose change.

josephw commented 2 months ago

This approach has worked well: I've incrementally migrated the codebase away from direct use of Log4j 1.x to pure SLF4J 2.x, without losing any existing structured logging, or needing any whole-codebase changes. It's now possible to move to another logging framework without changing the application code that's producing logs.

This is currently implemented with a fork of slf4j-reload4j, which could be dropped if this were applied, but that can go away as soon as the logging framework changes to something currently supported.