Java logging levels confusion

依然范特西╮ 提交于 2019-12-12 16:56:15

问题


I set logging level to CONFIG, but don't see messages written on CONFIG level. What I am missing?

Configuration:

Logger logger = java.util.logging.Logger.getLogger("xxx");
logger.setLevel(java.util.logging.Level.CONFIG);

Tests:

logger.log(java.util.logging.Level.SEVERE, "severe");
logger.log(java.util.logging.Level.WARNING, "warning");
logger.log(java.util.logging.Level.INFO, "info");
logger.log(java.util.logging.Level.CONFIG, "config");
logger.log(java.util.logging.Level.FINE, "fine");
logger.log(java.util.logging.Level.FINER, "finer");
logger.log(java.util.logging.Level.FINEST, "finest");

Output:

SEVERE: severe
WARNING: warning
INFO: info

回答1:


I typically use logback to implement logging, which seems a tad better documented. So I would recommend switching to that.

But to answer your question, I think what is happening is that your Logger is configured correctly, but the Handler it's sending its messages to isn't. The default configuration probably attaches a handler with INFO level logging to the root logger.

edit: I wrote a little test program to verify, you indeed need to set the level on the handler attached to the root logger. You can do so like this:

for (Handler handler : Logger.getLogger("").getHandlers()) {
    handler.setLevel(Level.CONFIG);
}
logger.config("config");

Gives as output:

Feb 11, 2011 4:32:14 PM Test main
CONFIG: config

This sets the level for all handlers attached to this. Obviously a better choice would be writing your own options file and explicitly configuring your loggers. A quick google turned up this article on the subject.

You could also try configuring with a properties file on your classpath that reads:

java.util.logging.ConsoleHandler.level=CONFIG



回答2:


This is the expected behavior.

When you define a level of logs, you will see all the logs of this level, but also the ones linked to higher level.

The order is the following:

  • SEVERE (highest value)
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST (lowest value)

So in your case, if you define the level to INFO, you will only see SEVERE, WARNING and INFO logs, and not CONFIG messages.


Edit, to answer your corrected question:

Maybe a third party library is used for your Logger class (log4j, slf4j, and so on), and this library defines its own level of log. For example, for log4j, there are only the following levels:

  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL

In such case, the level CONFIG is considered as a INFO level, that explains your current behavior.



来源:https://stackoverflow.com/questions/4970513/java-logging-levels-confusion

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