I've got a simple setup to log a message: JDK 8 Update 65
and Eclipse Mars
import java.util.logging.Logger;
public class Example {
private final static Logger LOGGER = Logger.getLogger(Example.class.getName());
public static void main(String[] args) {
LOGGER.info("Test");
}
}
I would expect to get an output on the stdout
, just like using System.out.println();
.
But instead it gets printed out on the stderr
, which results in a red font on the eclipse console:
I know that I can change this behavior by writing a custom Handler
, but I wish to know why the default output appears on the stderr
instead of stdout
?
A logger should use stdout
for fine
+info
and use stderr
for severe
level.
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).
来源:https://stackoverflow.com/questions/34156052/why-does-java-util-logging-logger-print-to-stderr