按需重新加载log4j2配置

jam*_*amp 16 java configuration logging log4j log4j2

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

<Configuration status="WARN" monitorInterval="30">
    ...
</Configuration>
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

jam*_*amp 23

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

((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).reconfigure();
Run Code Online (Sandbox Code Playgroud)

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


Rem*_*pma 5

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

更新:这是错误的。这里一个干净的方式,请参见下面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();
Run Code Online (Sandbox Code Playgroud)