In Log4j, what is the difference between NDC and MDC? Can I have a simple example where they are used?
相关问题
- I want to trace logs using a Macro multi parameter
- Error message 'No handlers could be found for
- convert logback.xml to log4j.properties
- Django management command doesn't show logging
- apache modules ap_log_perror is at a different lev
相关文章
- how do I log requests and responses for debugging
- Android Studio doesn't display logs by package
- Stacktrace does not print in Glassfish 4.1 Cluster
- Out of curiosity — why don't logging APIs impl
- Laravel log file based on date
- Java -How to get logger to work in shutdown hook?
- Codeigniter not logging
- Is there any way to remove the information line fr
To expand on the link which Sikorski put in the comments:
NDC
In NDC, the N stands for nested, meaning you control a single value with a Stack. You "push" a string, then you can "push" another whenever processing dictates; and when processing is complete you can pop it off to see the former value. This sort of contextual logging would be useful in some deeply-nested processing.
Setting the context string
This will get output in your log where you have the
%x
(lowercase) pattern:MDC
The M stands for mapped, and this gives you a different type of control. Instead of using a single stack to control a single contextual string, you use name/value pairs. This is useful for tracking multiple contextual bits, such as putting username and IP into the log.
Setting the mapped values:
Example MDC log4j pattern
Uppercase X with the example
"userIP"
and"userName"
strings. These must match in your code and in the log4j config:I would combine these into one )context string*.
Similarities and Differences
In both cases, whenever you do the
log.info("success");
, the output will have the additional context you have provided. This is much cleaner than concatenating strings likelog.info(req.getRemoteAddr()) + " success");
every time you log.Note that there are serious differences between the two with respect to threading and resources. In particular, NDC will keep handles to your threads which can affect the freeing of resources if you are not diligent about popping and clearing the NDC stack.
From the link: NDC use can lead to memory leaks if you do not periodically call the
NDC.remove()
method.MDC allows you to add custom tags for log4j. eg:
is referenced by
MDC child thread automatically inherits a copy of the mapped diagnostic context of its parent.
NDC operations such as
push
,pop
,clear
,getDepth
andsetMaxDepth
affect the NDC of the current thread only.