简体   繁体   中英

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

I am now using log4j2 in xml configuration. 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. Since the log4j cannot know does the date change.

The filename attribute is evaluated only once when the configuration is created. The filePattern attribute is evaluated on every rollover. 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. However, if a lookup is coded as $${date} then then first evaluation will simply remove the leading '$'. 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 . 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. 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}

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