在log4j中记录用户名[英] Logging username in log4j

本文是小编为大家收集整理的关于在log4j中记录用户名的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要在logs.in log4j中使用MDC的第一个线程打印用户名.任何人都可以建议如何进一步进行此操作.

推荐答案

mdc a href =" http://docs.oracle.com/javase/7/docs/api/java/java/lang/threadlocal.html" rel =" nofollow"> ThreadLocal to存储值.也许log4j(如 logback )使用 InheritableThreadLocal 哪些部分求解了类似您的问题:新创建的线程从父元线程继承MDC.

我想您正在使用某种合并(我们很少在EE环境中创建专用线程,因此继承MDC不仅没有帮助,而且当池按需增长时可能会引起很多混乱).不幸的是,在这种情况下,您需要在切换到新线程时明确设置MDC.更重要的是,您需要清理后,否则池线程将被旧的MDC"污染".

例如,在包含有效MDC值的Web线程发送JMS消息时,您必须添加所需的MDC值,例如进入消息标题.然后,当您收到JMS消息(在JMS线程中)时,您需要手动检验此值并注册它们:

public void onMessage(Message message) {
    MDC.put("user", message.getStringProperty("user"));
    try {
        //handle the message
    } finally {
        MDC.clear();
    }
}

每次请求跳入其他线程时,您都必须执行类似的注册.再一次 - 清理非常重要.很重要.

本文地址:https://www.itbaoku.cn/post/1575145.html

问题描述

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 .

推荐答案

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.