简体   繁体   English

如何在执行时更改log4j2中的日志路径

[英]How to change log path in log4j2 at execution time

Hi I am using slf4j over log4j2. 嗨我在log4j2上使用slf4j。 How do I change log path dynamically? 如何动态更改日志路径?

My log4j2.xml looks like 我的log4j2.xml看起来像

   <Properties>
        <Property name="home">/path/logs</Property>
    </Properties>
    <Appenders>
        <RollingFile name="default" fileName="${home}/error.log"
                     filePattern="...">
               .......

        </RollingFile>
    </Appenders>

Is there any way I can change the path where logs will be written at runtime? 有什么办法可以改变运行时写入日志的路径吗?

I tried with having system property in the path and setting it in runtime but log4j2 does not consider the updated value. 我尝试在路径中使用系统属性并在运行时设置它,但log4j2不考虑更新的值。 System properties approach- 系统属性方法 -

<RollingFile name="default" fileName="${sys:home}/error.log"
                     filePattern="...">

(In java class: System.setProperty("home","/newPath"))

Does this require reconfiguration. 这是否需要重新配置。 I don't see any exposed service of slf4j to reconfigure. 我没有看到重新配置slf4j的任何公开服务。

Use DOMConfigurator.doConfigure() , where the second parameter is LogManager.getLoggerRepository() . 使用DOMConfigurator.doConfigure() ,其中第二个参数是LogManager.getLoggerRepository() This way you can change not just logging path, but everything else too, including levels for specific loggers, for example. 这样,您不仅可以更改日志记录路径,还可以更改其他所有内容,例如,包括特定记录器的级别。

I don't think you can reconfigure SLF4j implementation using "implementation-agnostic" way. 我不认为您可以使用“与实现无关”的方式重新配置SLF4j实现。 When we switched our application from Log4j to Logback, we also changed the way configuration file is re-read in runtime. 当我们将应用程序从Log4j切换到Logback时,我们还改变了在运行时重新读取配置文件的方式。 For Logback this uses JoranConfigurator.doConfigure() . 对于Logback,它使用JoranConfigurator.doConfigure()

The only solution i got is using context variable. 我得到的唯一解决方案是使用上下文变量。

MDC.put("logLocation","path/to/log")

In log4j2.xml 在log4j2.xml中

<RollingFile name="default" fileName="${ctx:logLocation}/error.log"
                 filePattern="...">

However the catch is , for each thread the context should have this variable(logLocation) set 但是,对于每个线程,上下文应该设置此变量(logLocation)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM