简体   繁体   English

Log4j2:如何为每一天创建一个新的日志文件夹?

[英]Log4j2: How to create a new log folder for each day?

I am now using log4j2 in xml configuration.我现在在 xml 配置中使用 log4j2。 Then I found that whatever using然后我发现无论使用

<RollingFile name="DailyLog" fileName="${baseDir}/${date:yyyyMM}/${date:dd}/daily.log"
                 filePattern="${baseDir}/${date:yyyyMM}/${date:dd}/daily.%d{yyyy-MM-dd}.%i.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss}{UTC} %level: %msg %n"/>
        <Policies>
            <OnStartupTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="10 MB"/>
            <TimeBasedTriggeringPolicy interval="1" modulate="false"/>
        </Policies>
    </RollingFile>

Each TriggeringPolicy will only make the file name change (But not the folder) The daily folder will be create if I restart program every day.每个 TriggeringPolicy 只会更改文件名(但不会更改文件夹)如果我每天重新启动程序,将创建每日文件夹。 Since the log4j cannot know does the date change.由于 log4j 无法知道日期是否更改。

The filename attribute is evaluated only once when the configuration is created.文件名属性仅在创建配置时评估一次。 The filePattern attribute is evaluated on every rollover.每次翻转时都会评估 filePattern 属性。 Lookups, such as the date lookup you are using, can be evaluated multiple times.可以多次评估查找,例如您正在使用的日期查找。 The first evaluation happens when the configuration is evaluated, so all of your ${date} lookups are being evaluated when the configuration is created.第一次评估发生在评估配置时,因此您的所有 ${date} 查找都在创建配置时进行评估。 However, if a lookup is coded as $${date} then then first evaluation will simply remove the leading '$'.但是,如果查找编码为 $${date},那么第一次评估将简单地删除前导“$”。 Then when the pattern is evaluated on each rollover the date lookup will resolve to whatever the current date is.然后,当在每次翻转时评估模式时,日期查找将解析为当前日期。

If you desire to have the current file log to a directory with the current date then your best option is to use the DirectWriteRolloverStrategy .如果您希望将当前文件记录到具有当前日期的目录,那么您最好的选择是使用DirectWriteRolloverStrategy This can be achieved simply by removing the fileName attribute, in which case logs will be written to a file matching the current file pattern.这可以简单地通过删除 fileName 属性来实现,在这种情况下,日志将被写入与当前文件模式匹配的文件中。 In your case, that would look like在你的情况下,这看起来像

<RollingFile name="DailyLog"
                 filePattern="${baseDir}/$${date:yyyyMM}/$${date:dd}/daily.%d{yyyy-MM-dd}.%i.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss}{UTC} %level: %msg %n"/>
        <Policies>
            <OnStartupTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="10 MB"/>
            <TimeBasedTriggeringPolicy interval="1" modulate="false"/>
        </Policies>
    </RollingFile>

I use Logback.我使用登录。

<fileNamePattern>${LOG_PATH}/info.log.%d{yyyy-MM-dd}

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

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