java – log4j2 – 如何动态更改文件?

我已经使用log4j 2实现了异步日志记录,但现在我需要每小时更改一次日志文件名,例如2015-11-19 / log-12.00.log,2015-11-19 / log-13.00等.(Soulutions I’发现没有工作,可能是我做错了什么).

我有以下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>

如何实现这一目标?

最佳答案 你应该看看TimeBasedTriggeringPolicy.基本上,一旦日期/时间模式不再适用于活动文件,它就会导致翻转.

没试过,但这对你有用.

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

TimeBasedTriggeringPolicy interval属性根据日期模式中最具体的时间单位控制翻转的频率.在你的情况下,文件模式的小时数是%d {HH}.

点赞