更改Logger实例的全局设置 [英] Change global setting for Logger instances
问题描述
我正在使用 java.util.logging.Logger 作为我的应用程序的日志引擎。每个类使用它自己的记录器,即每个类具有:
I'm using java.util.logging.Logger as the logging engine for my application. Each class uses it's own logger, i.e., each class has:
private final Logger logger = Logger.getLogger(this.getClass().getName());
我想为我的所有类设置日志记录级别,并且能够更改它(即,将设置放在一个地方)。有没有办法做到这一点,其他使用全局 Level
变量并手动设置每个记录器?
I want to set a logging level for all my classes, and be able to change it (i.e., have the setting in one place). Is there a way to do this, other that using a global Level
variable and manually set each logger to it?
推荐答案
正如Andy 回答,在大多数情况下,您应该使用属性文件和VM参数,因此它独立于您的代码。
As Andy answered, in most cases you should use the property file and the VM argument, thus its independent from your code.
但是如果您想出于某种原因以编程方式进行(我自己在一个案例中有充分理由)您可以访问像这样的处理程序:
But if you want to go programatically for some reason (I myself had a good reason in one case) you can access the Handlers like this too:
Logger rootLogger = LogManager.getLogManager().getLogger("");
rootLogger.setLevel(Level.INFO);
for (Handler h : rootLogger.getHandlers()) {
h.setLevel(Level.INFO);
}
编辑我将setLevel添加到根记录器正如searchengine27在他的回答中指出的那样。
EDIT I added the setLevel to the root logger as searchengine27 pointed out in in his answer.
处理程序是您通过属性或以编程方式设置的文件或控制台处理程序。
The Handlers are File or Console Handlers that you setup via the properties or programatically too.
或更改此类过滤器:
Logger rootLogger = LogManager.getLogManager().getLogger("");
rootLogger.setFilter(new Filter() {
@Override
public boolean isLoggable(LogRecord record) {
return "something".equals(record.getLoggerName());
}
});
这篇关于更改Logger实例的全局设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!