简体   繁体   中英

log4j2 - how to change file dynamically?

I've implemented async logging with log4j 2, but now I need to change log filename every hour, eg 2015-11-19/log-12.00.log, 2015-11-19/log-13.00, etc. (Soulutions I've found didn't work, may be I did something wrong).

I have following log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- Don't forget to set system property
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
     to make all loggers asynchronous. -->

<Configuration status="WARN">
    <Appenders>
        <!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
        <RandomAccessFile name="RandomAccessFile" fileName="async.log" immediateFlush="false" append="true">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
            </PatternLayout>
        </RandomAccessFile>
    </Appenders>
    <Loggers>
        <Root level="info" includeLocation="false">
            <AppenderRef ref="RandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>

How to achive this?

You should have a look at TimeBasedTriggeringPolicy . Basically it causes a rollover once the date/time pattern no longer applies to the active file. Have't tried this but this should work for you.

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN" >
<appenders>
    <Async name="Async">
        <AppenderRef ref="logfile" />
    </Async>

    <RollingRandomAccessFile name="logfile" fileName="async.log" filePattern="log-%d{HH}.00.log">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"/>
        </Policies>
        <DefaultRolloverStrategy max="24"/>
    </RollingRandomAccessFile>
</appenders>
<loggers>
    <root level="INFO" includeLocation="false">
        <AppenderRef ref="Async"/>
    </root>
</loggers>
</configuration>

The TimeBasedTriggeringPolicy interval attribute controls how often a rollover should occur based on the most specific time unit in the date pattern. In you case it is hours that is %d{HH} from file pattern.

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