问题描述
我需要在日志中打印用户名和客户端IP地址,但用户名仅在log4j中使用MDC的第一个线程打印.从下一个线程开始,值打印为空.任何人都可以建议如何进一步进行此操作.
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 使用 ThreadLocal
存储值.也许Log4J(例如 Logback )使用 InheritableThreadLocal
部分解决了像您这样的问题:新创建的线程从父线程继承了MDC.
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.
我猜您正在使用某种类型的池(我们很少在EE环境中创建专用线程,因此继承MDC不仅无济于事,而且当池按需增长时可能会引起很多混乱).不幸的是,在这种情况下,切换到新线程时需要显式设置MDC.更重要的是,您需要对其进行清理,否则池线程将被旧的MDC污染".
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.
例如,当从包含有效MDC值的Web线程发送JMS消息时,您必须添加所需的MDC值,例如放入邮件标题中.然后,当您收到一条JMS消息(在JMS线程中)时,您需要手动检索此值并注册它们:
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.
这篇关于在log4j中记录用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!