更改 Logger 实例的全局设置 [英] Change global setting for Logger instances

查看:24
本文介绍了更改 Logger 实例的全局设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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);
}

编辑我在他的 answer.

处理程序是您通过属性或以编程方式设置的文件或控制台处理程序.

The Handlers are File or Console Handlers that you setup via the properties or programatically too.

或者像这样更改过滤器:

Or change filters like this:

Logger rootLogger = LogManager.getLogManager().getLogger("");
rootLogger.setFilter(new Filter() {
    @Override
    public boolean isLoggable(LogRecord record) {
            return "something".equals(record.getLoggerName());
    }
});

这篇关于更改 Logger 实例的全局设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆