简体   繁体   中英

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. So lets say there are 2 Threads in my pool. Right now, log4j is used for logging. It writes all threads' logs into single file and all 2 threads' log data is interleaved.

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就像它在这里描述的那样

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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