跨多个线程的Java日志记录 [英] Java logging across multiple threads

查看:567
本文介绍了跨多个线程的Java日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用线程的系统,因此它可以并行处理并行的不同功能.我们希望找到一种方法,将特定交易"的所有日志条目捆绑在一起.通常,人们可能会使用"threadName"将它们收集在一起,但显然在多线程情况下会失败.

We have a system that uses threading so that it can concurrently handle different bits of functionality in parallel. We would like to find a way to tie all log entries for a particular "transaction" together. Normally, one might use 'threadName' to gather these together, but clearly that fails in a multithreaded situation.

在每个方法调用中向下传递一个事务键"的短暂时间,我看不到将它们绑定在一起的方法.而且将密钥传递到每个方法中都是很丑陋的.

Short of passing a 'transaction key' down through every method call, I can't see a way to tie these together. And passing a key into every single method is just ugly.

此外,由于我们的系统基于Java的修改版本,因此我们与Java日志紧密联系在一起.因此,我将对其他平台感兴趣,以作为我们可以尝试的示例,但是切换平台的可能性很小.

Also, we're kind of tied to Java logging, as our system is built on a modified version of it. So, I would be interested in other platforms for examples of what we might try, but switching platforms is highly unlikely.

有人有什么建议吗?
谢谢,
彼得

Does anyone have any suggestions?
Thanks,
Peter

不幸的是,我无法控制线程的创建,因为这全部由工作流程包处理.否则,最好为每个线程(在ThreadLocal上?)缓存一次ID,然后在创建新线程时对其进行设置,这是一个好主意.我仍然可以尝试.

Unfortunately, I don't have control over the creation of the threads as that's all handled by a workflow package. Otherwise, the idea of caching the ID once for each thread (on ThreadLocal maybe?) then setting that on the new threads as they are created is a good idea. I may try that anyway.

推荐答案

但是,您提到您的事务跨越多个线程,请看一下log4j如何通过MDC将附加信息绑定到当前线程,以及NDC类.正如您之前所建议的那样,它使用ThreadLocal,但是有趣的是log4j如何将数据注入日志消息中.

However you mentioned that your transaction spans more than one thread, take a look at how log4j cope with binding additional information to current thread with MDC and NDC classes. It uses ThreadLocal as you were advised before, but interesting thing is how log4j injects data into log messages.

//In the code:

//In the code:

MDC.put("RemoteAddress", req.getRemoteAddr());

MDC.put("RemoteAddress", req.getRemoteAddr());

//In the configuration file, add the following:

//In the configuration file, add the following:

%X{RemoteAddress}

%X{RemoteAddress}

详细信息:

http://onjava.com /pub/a/onjava/2002/08/07/log4j.html?page=3

http://wiki.apache.org/logging-log4j/NDCvsMDC

这篇关于跨多个线程的Java日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆