简体   繁体   中英

How to change log path in log4j2 at execution time

Hi I am using slf4j over log4j2. How do I change log path dynamically?

My log4j2.xml looks like

   <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. 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.

Use DOMConfigurator.doConfigure() , where the second parameter is 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. When we switched our application from Log4j to Logback, we also changed the way configuration file is re-read in runtime. For Logback this uses JoranConfigurator.doConfigure() .

The only solution i got is using context variable.

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

In 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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