从多个线程进行Java日志记录的最佳实践? [英] Best practices for Java logging from multiple threads?

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

问题描述

我想要一个由管理数据的多个任务生成的诊断日志。这些任务可能在多个线程中。每个任务都需要将一个元素(可能带有子元素)写入日志;进去快点出去。如果这是单任务情况,我会使用 XMLStreamWriter ,因为它似乎是简单/功能的最佳匹配,而无需在内存中保存不断膨胀的XML文档。

I want to have a diagnostic log that is produced by several tasks managing data. These tasks may be in multiple threads. Each task needs to write an element (possibly with subelements) to the log; get in and get out quickly. If this were a single-task situation I'd use XMLStreamWriter as it seems like the best match for simplicity/functionality without having to hold a ballooning XML document in memory.

但这不是单任务情况,我不确定如何最好地确保这是线程安全,其中线程安全在此应用程序中意味着每个日志元素应该正确且连续地写入日志(一个接一个,不以任何方式交错)。

But it's not a single-task situation, and I'm not sure how to best make sure this is "threadsafe", where "threadsafe" in this application means that each log element should be written to the log correctly and serially (one after the other and not interleaved in any way).

有什么建议吗?我有一个模糊的直觉,要走的路是使用一个日志元素队列(每个元素都可以快速生成:我的应用程序正在忙于执行对性能敏感的实际工作),并且有一个单独的线程来处理日志元素并将它们发送到一个文件,因此日志记录不会中断生成器。

Any suggestions? I have a vague intuition that the way to go is to use a queue of log elements (with each one able to be produced quickly: my application is busy doing real work that's performance-sensitive), and have a separate thread which handles the log elements and sends them to a file so the logging doesn't interrupt the producers.

日志记录不一定是XML,但我确实希望它是结构化和机器可读。

The logging doesn't necessarily have to be XML, but I do want it to be structured and machine-readable.

编辑:我将threadsafe放在引号中。 Log4j似乎是一个显而易见的选择(对我来说很新但对社区来说很老),为什么重新发明轮子......

edit: I put "threadsafe" in quotes. Log4j seems to be the obvious choice (new to me but old to the community), why reinvent the wheel...

推荐答案

使用日志框架,例如 Log4j

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

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