What's is idiomatic way of setting message-specific properties in log4j2 in multi-threading application ?
My server allows external developers to create plugins for it. These plugins would be used for periodic jobs which represented by (reactive streams) Flux<> class.
I'd like my service to allow plugin developers to log events. But I want to define context-specific properties to these jobs (e.g. JobID). There could be multiple simultenious jobs running at the same time.
Typically people use log4j's MDC
/ThreadContext
for this. But because server is built using reactive streams different steps of "job" can be executed in different threads.
At the moment I've implemented very hacky workaround. I dictate plugin developers to use
interface TelemetryFactory {
fun getLogger(clazz: Class<*>): Logger
fun getLogger(name: String): Logger
}
to create instance of the Logger. In implementation of this interface I wrap MessageFactory2.newMessage()
calls by calling ThreadContext.putAll()
with my context-specific fields.
class MessageFactory2Wrapper(private val fields: Map<String, String>): MessageFactory2 {
...
}
This works only because I see in source-code of log4j that default message factory is ReusableMessageFactory
therefore message and thread-context will reach appenders before subsequent logger call will change ThreadContext
.
I wish org.apache.logging.log4j.message.Message
had some kind of Map<String, String>
that I can use in loging layout.
What should I do ?
question from:https://stackoverflow.com/questions/66049925/whats-is-idiomatic-way-of-setting-message-specific-properties-in-log4j2