简体   繁体   English

如何以同步方式为不同的Interleaved线程进行Java日志记录?

[英]How to do Java Logging for different Interleaved threads in synchronous way?

I would like to explain my problem directly with example. 我想用例子直接解释我的问题。 Please add comments if some other information is also required. 如果还需要其他信息,请添加评论。

I have a small application(SpringBoot+Java), and it uses ThreadPool for executing several Tasks. 我有一个小应用程序(SpringBoot + Java),它使用ThreadPool来执行几个任务。 So lets say there are 2 Threads in my pool. 所以假设我的池中有2个线程。 Right now, log4j is used for logging. 现在,log4j用于记录。 It writes all threads' logs into single file and all 2 threads' log data is interleaved. 它将所有线程的日志写入单个文件,并且所有2个线程的日志数据都是交错的。

So each thread works like - 所以每个线程都像 -

[Thread-1][08:15:00] entered into application
[Thread-1][08:15:00] entered method A
[Thread-1][08:15:05] exit method A
[Thread-1][08:15:10] entered method B
[Thread-1][08:15:15] exit method B
[Thread-1][08:15:30] exit from application

[Thread-2][08:15:01] entered into application
[Thread-2][08:15:01] entered method A
[Thread-2][08:15:04] exit method A
[Thread-2][08:15:11] entered method B
[Thread-2][08:15:12] exit method B
[Thread-2][08:15:22] exit from application

but my log file has these entries on basis of timestamp- 但是我的日志文件在时间戳的基础上有这些条目 -

[Thread-1][08:15:00] entered into application
[Thread-1][08:15:00] entered method A
[Thread-2][08:15:01] entered into application
[Thread-2][08:15:01] entered method A
[Thread-2][08:15:04] exit method A
[Thread-1][08:15:05] exit method A
[Thread-1][08:15:10] entered method B
[Thread-2][08:15:11] entered method B
[Thread-2][08:15:12] exit method B
[Thread-2][08:15:14] exit from application
[Thread-1][08:15:15] exit method B
[Thread-1][08:15:30] exit from application

I want my log file to print thread wise execution, and not timestamp wise. 我希望我的日志文件打印线程执行,而不是时间戳明智。 I want my log file to print each thread completely before other thread starts. 我希望我的日志文件在其他线程启动之前完全打印每个线程。 How could i achieve this. 我怎么能实现这一点。

I have already searched and found below article as the closest, but i dont want different log files- How to log multiple threads in different log files? 我已经搜索并发现下面的文章是最接近的,但我不想要不同的日志文件 - 如何在不同的日志文件中记录多个线程?

I need to output all log data into single log file grouped by thread name, and sorted by thread start time. 我需要将所有日志数据输出到按线程名称分组的单个日志文件中,并按线程开始时间排序。

我想在控制台appender中分离日志是行不通的我建议为每个Thread定义单独的FileAppenders就像它在这里描述的那样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM