Logging username in log4j

狂风中的少年 提交于 2019-12-25 02:18:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!