在java中登录多线程应用程序 [英] Logging in multi-threaded application in java

查看:278
本文介绍了在java中登录多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于登录多线程环境的最佳方法和最佳工具是什么,以便每个线程都拥有自己的记录器实例和单独的文件。这有可能吗?

What's the best way and best tool for logging in multi-threaded environment, so that each thread has it's own logger instance and separate file. is this even possible?

推荐答案

您可以尝试使用自定义Log4J appender,它将线程ID作为参数并根据线程调用它来过滤消息。即时创建它,将其附加到记录器。

You may try using a custom Log4J appender, which takes thread id as a parameter and filters messages based on what thread calls it. Create it on the fly, attach it to the logger.

这种方法存在多个问题:

There are multiple problems with this approach though:


  1. 太多的appender会减慢日志记录

  2. AppServer通常有一个线程池。这意味着随着时间的推移,同一个线程将参与执行完全不相关的请求,这些请求将最终出现在同一个日志文件中。

我建议你考虑一种更简单的方法:将线程id记录到同一个日志文件中。它快速而简单,log4j有一个%标志。稍后,如果需要,您可以按线程ID grep /拆分日志文件。

I suggest you consider a simpler approach: log thread id into the same log file. It's fast and simple, log4j has a % flag for doing it. Later you can grep/split the log file per thread id if required.

更新

实际上,你可能有一个自定义appender,它会在新线程记录一条记录时按需打开日志文件(appender在该线程上下文中执行,只需调用Thread.currentThread()。getName()) 。但是您必须重新实现所有常规日志文件任务(轮换)或将其委托给每个文件的标准appender。

Actually, you may have a single custom appender, which will open log files on demand when a new thread logs a record (the appender is executed within that thread context, just call Thread.currentThread().getName()). But you'll have to re-implement all usual log file tasks (rotation) or delegate it to standard appender for each file.

这篇关于在java中登录多线程应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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