Question

I have a logging mechanism setup with Slf4j and java.util.Logging. I have several threads so I'm unable to get a clear idea from logs since they are mixed. Now I try to use MDC concept to add some more data with the log file so they are clear.

Problem is as in Slf4j though it supports MDC java.util.Logging does not. But it says

If the underlying framework does not offer MDC, for example java.util.logging, then SLF4J will still store MDC data but the information therein will need to be retrieved by custom user code.

I'm trying to find a way to do this custom code. Googling does not help me much. There is a helper class in Slf4j named "BasicMDCAdapter". But I don't know how to use it. I couldn't find a sample code anywhere.

This is also a code to help with this but still doesn't give bit of description.

I appreciate a help from some one here.

Thank you.

Was it helpful?

Solution

Depending on what you'd like to achieve you might be able to avoid custom code at all.

Use the JUL to SLF4J Bridge

The is a bridge available that hooks into java.util.Logging (JUL) and forwards all log events to SLF4J. Using the log output allows to use any SLF4J logging implementation (such as Logback or Log4j) for writing the combined log output for both logging APIs.

Using the JUL to SLF4J Bridge you'll get MDC support for free with any SLF4J implementation supporting it.

Write a JUL Extension

If you want to keep the logging systems separated then you would need to write a JUL extension which "reads" the MDC and output its values into the log. If you look into the SLF4J MDC class, it has a method for accessing all its values: org.slf4j.MDC.getCopyOfContextMap().

Keep in mind that the default JUL handler are very limited. Thus I think you would have to implement your own, which could then access the MDC. However, you need to check first that they are called from within the same thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top