问题
I need to print username and client IP address in logs.but username is only prints for first thread using MDC in log4j.From next thread the values are printed as empty. can any one suggest how to proceed further on this .
回答1:
MDC uses ThreadLocal to store values. Maybe Log4J (like Logback) uses InheritableThreadLocal which partially solves problems like yours: newly created thread inherits MDC from parent thread.
I guess you are using some sort of pooling (we are rarely creating dedicated threads in EE environment, so inheriting MDC not only does not help, but might cause a lot of confusion when the pool grows on demand). Unfortunately in this case you need to set MDC explicitly when switching to new thread. Even more important, you need to clean up after it, otherwise the pool thread will be "polluted" with old MDC.
For example when sending a JMS message from web thread containing valid MDC value you must add desired MDC values e.g. into messages headers. Then, when you receive a JMS message (in JMS thread), you need to retrive this values manually and register them:
public void onMessage(Message message) {
MDC.put("user", message.getStringProperty("user"));
try {
//handle the message
} finally {
MDC.clear();
}
}
You must perform similar registration every time your request jumps into a different thread. Once again - clean up is very important.
来源:https://stackoverflow.com/questions/8554172/logging-username-in-log4j