How do I change java logging console output from std err to std out?

后端 未结 13 1629
旧巷少年郎
旧巷少年郎 2020-11-27 06:50

I\'m using the standard ConsoleHandler from java.util.logging and by default the console output is directed to the error stream (i.e. System.

13条回答
  •  天命终不由人
    2020-11-27 07:29

    I had a similar problem. I wanted to log INFO and below to System.out, and WARNING and above to System.err. Here is the solution I implemented:

    public class DualConsoleHandler extends StreamHandler {
    
        private final ConsoleHandler stderrHandler = new ConsoleHandler();
    
        public DualConsoleHandler() {
            super(System.out, new SimpleFormatter());
        }
    
        @Override
        public void publish(LogRecord record) {
            if (record.getLevel().intValue() <= Level.INFO.intValue()) {
                super.publish(record);
                super.flush();
            } else {
                stderrHandler.publish(record);
                stderrHandler.flush();
            }
        }
    }
    

    Of course, you could make it more flexible by factoring out the hard-coded reference to Level.INFO, for example. But this worked well for me to get some basic dual-stream logging. (BTW, the tips about not subclassing ConsoleHandler to avoid closing the System.err were very useful.)

提交回复
热议问题