简体   繁体   中英

How does Log4j2 DefaultRolloverStrategy's max attribute really work?

I've configured a RollingRandomAccessFileAppender with only the OnStartupTriggeringPolicy set, but when I set the max attribute of the DefaultRolloverStrategy to some number, the logs keep generating past that amount indefinitely.

Here's my log4j2.xml :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingRandomAccessFile 
            name="RollingRAF" 
            fileName="logs/app.log"
            filePattern="logs/app-%d{dd-MMM-yyyy@HH.mm.ss}.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy max="5"/>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <Logger name="myLogger" level="warn">
            <AppenderRef ref="RollingRAF"/>
        </Logger>
        <Root level="error">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Is it because I don't have an iterator in my name pattern?

Is it because my file name precision is set to seconds?

Is it because I only have the OnStartupTriggeringPolicy set?

Or what's going on here?

My goal here was to set up a rolling configuration that will log the last 5 application runs.

The DefaultRolloverStrategy will use the date pattern specified in the filePattern if a TimeBasedTriggeringPolicy is specified. To use the max attribute, specify a %i pattern in the filePattern, and add <SizeBasedTriggeringPolicy size="20 MB" /> to the rollover policies. (Or some other size of course.)

The value for max in <DefaultRolloverStrategy max="5"/> will then ensure that within the same rollover period (one second for you since you specified a date pattern of %d{dd-MMM-yyyy@HH.mm.ss} ) no more than 5 files will be created when a size-based rollover was triggered.

This is more useful if your rollover window is longer, like rolling over to a new folder every day, and within that folder, ensure that no more than 5 files are created with max size=20 MB.


Update:

Log4j 2.5 added the ability to configure custom delete actions . Out of the box you can delete files based on age, count or how much disk space they take up (accumulated file size).

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