MDC(Mapped Diagnostic Context) support for JUL(Java.util.Logging)
Asked Answered
O

1

10

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.

Outplay answered 29/5, 2013 at 10:49 Comment(1)
I hate to give the answer "try something else", but... Have you tried using logback? It's a logger built specifically to support slf4j and it has mdc support. <dependency><br/> <groupId>ch.qos.logback</groupId><br/> <artifactId>logback-classic</artifactId><br/> <version>0.9.30</version><br/> </dependency><br/> <dependency><br/> <groupId>ch.qos.logback</groupId><br/> <artifactId>logback-core</artifactId><br/> <version>0.9.30</version><br/> </dependency><br/>Convex
K
10

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.

Knorring answered 8/6, 2013 at 7:29 Comment(2)
So how would one use MDC without adding an explicit dependency on slf4j?Insuperable
@Insuperable Please ask a new question as new questions and not in comments. This answer is in the context of the original question, which does have SLF4J available.Knorring

© 2022 - 2024 — McMap. All rights reserved.