Why does java.util.logging.Logger print to stderr?

梦想的初衷 提交于 2019-11-30 19:01:03
Jose A. Rodríguez Salor

By default, the logger outputs log records of level INFO and above (i.e., INFO, WARNING and SEVERE) to standard error stream (System.err).

Source: www3.ntu.edu.sg/home/ehchua/programming/java/JavaLogging.html

It is well documented. By default, loggers publish to their parent's handlers, recursively up to the tree, until the other handler has been specified. You can loop over the parent's handlers and see that the default handler of the parent's logger is ConsoleHandler which uses System.err to publish log records.

public class Main {
    public static void main(String[] args) {
        Handler[] handlers = Logger.getLogger(Main.class.getName()).getParent().getHandlers();
        for (Handler handler : handlers) {
            System.out.println(handler.getClass().getName());
        }
    }
}

The java.util.logging API was developed under JSR 47: Logging API Specification. According to the change log in the "Proposed Final Draft" the ConsoleHandler always used System.err. The JCP page also lists the original authors of the API and I think only those names truly know the answer to your question.

I would imagine the origin comes from the mindset that logging is for reporting failures and failure reporting gets directed to System.err. Really for the ConsoleHandler, any level above INFO should go to error stream and any level INFO or less should go to out stream if you are trying to maintain precedents of the JDK prior to addition of logging API.

You can create and extended ConsoleHandler to set the out to System.out instead of System.err

Logger logger = Logger.getLoger("your_logger_name");
logger.setUseParentHandler(false);
logger.addHandler(new ConsoleHandler() {
    {setOutputStream(System.out);}
});

Now all message on this logger will appear in the System.out console.

the reason they use stderr is because this stream "is used for error messages and diagnostics issued by the program" (source: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!