简体   繁体   中英

logback: Race condition when logging to System.out & err

I try to configure logback in a way that loggs errors to System.err while other log events are logged to System.out. The best I've come up with so far is to define two appenders with filters. This solves the main problem but introduces a new one I'd like to avoid: With two appenders it sometimes happens that the order in which the log events were meant to be logged gets mixed up.
Example:
In code: Info log followed by an error log.
On console: Error gets logged to console before the info event.

I'm interested in any and all ideas how to avoid this problem while still logging errors to System.err and the rest to System.out.

I am afraid you can not generally enforce the "correct" ordering in this case. The messages are written to two different streams, which get independently flushed to the output medium, and it depends on many things, which are not in control of your code or the logback, how exactly the content of the two streams get mixed on the output. Just try a simple example:

    while(true) {
        System.out.println("XXX");
        System.err.println("YYYYYY");
    }

Although my code is synchronous, the XXX and YYYYY strings get randomly mixed on my console (clusters of "XXX" or "YYYYYY" lines are printed randomly). And logback is doing something similar under the hood and can not enforce how your console prints out the two separate streams.

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