java 按需重新加载 log4j2 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28216310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:12:28  来源:igfitidea点击:

Reload log4j2 configuration on demand

javaloggingconfigurationlog4jlog4j2

提问by jamp

I have my log4j2.xml config file set to be checked every 30 seconds:

我将 log4j2.xml 配置文件设置为每 30 秒检查一次:

<Configuration status="WARN" monitorInterval="30">
    ...
</Configuration>

Is it possible to programmatically tell log4j2 to check for changes in the configuration instead of having a timeout?

是否可以以编程方式告诉 log4j2 检查配置中的更改而不是超时?

N.B.I don't want to programmatically load the configuration specifying the config file, I just want to tell log4j2 to check the config file that has been loaded before as if the monitorInterval expired.

NB我不想以编程方式加载指定配置文件的配置,我只想告诉log4j2检查之前加载的配置文件,就好像monitorInterval过期一样。

Thanks!

谢谢!

回答by jamp

It looks like I've found the solution:

看起来我已经找到了解决方案:

((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).reconfigure();

Does anyone see anything wrong/side-effects with this?

有没有人看到任何错误/副作用?

回答by Remko Popma

There is currently no clean way to do this. It can be done with reflection. (Of course this may break if the implementation changes.)

目前没有干净的方法来做到这一点。它可以通过反射来完成。(当然,如果实现发生变化,这可能会中断。)

UPDATE: this is wrong. There isa clean way, see jamp's answer below.

更新:这是错误的。这里一个干净的方式,请参见下面JAMP的答案。

org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);

org.apache.logging.log4j.core.config.FileConfigurationMonitor mon = (org.apache.logging.log4j.core.config.FileConfigurationMonitor) ctx.getConfiguration().getConfigurationMonitor();

// use reflection to get monitor's "nextCheck" field.
// set field accessible
// set field value to zero

mon.checkConfiguration();