How to delete old log4j2 logs, saving up to 10 files?

I want to:

  • Maximum 10 log files, total
  • Each log file is no larger than 50 MB.

Thus, the log folder never grows (50 MB * 10) = 500 MB.

But it looks like my log4j2 configuration is wrong.

What's happening:

  • Logs End After 50 MB
  • But there are up to 10 magazines per day
  • Thus, the number of log files stored in the log folder is not limited (since, for example, after 2 days 20 logs of 50 mb each were collected)

Here is the configuration:

<Configuration status="WARN"> <Appenders> <RollingFile name="RollingFile" fileName="log/my.log" filePattern="log/my-%d{MM-dd-yyyy}-%i.log"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> <Policies> <OnStartupTriggeringPolicy /> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="50 MB"/> </Policies> <DefaultRolloverStrategy max="10"/> </RollingFile> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="RollingFile"/> </Root> </Loggers> </Configuration> 

What am I doing wrong?

+5
source share
2 answers

Starting with version 2.5, Log4j supports a custom delete action , which is performed with each poll.

You can control which files are deleted:

  • Name ( glob or regex mapping)
  • Age ("remove if 14 days or older")
  • Count ("keep only the last 3")
  • Size ("save only the latest files up to 500 MB")

The above may be combined. Instead of specifying only a size condition to maintain disk space up to a maximum of 500 MB, it is recommended that you also map the name so that you do not accidentally delete unrelated files.

Users who need even finer-grained control over which files to delete can specify a script condition using any supported JSR-223 scripting language.

Please check the documentation , it has three complete examples that may be useful.

For your question, this snippet may work:

  <DefaultRolloverStrategy> <!-- * only files in the log folder, no sub folders * only rolled over log files (name match) * either when more than 10 matching files exist or when the max disk usage is exceeded --> <Delete basePath="log" maxDepth="1"> <IfFileName glob="my-??-??-????-*.log"> <IfAny> <IfAccumulatedFileSize exceeds="500 MB" /> <IfAccumulatedFileCount exceeds="10" /> </IfAny> </IfFileName> </Delete> </DefaultRolloverStrategy> 

As a note, note that compress log files when capsizing so they take up less disk space.

Finally, be careful! Unable to recover files deleted this way. :-)

+4
source

TimeBasedTriggeringPolicy is based on filePattern . Basically, the smallest unit of time in a file template ( %d ) is the start time interval. In your case, the value is "dd", therefore, the policy runs every day.

Having% i in your filePattern stores several log files throughout the day. I would recommend trying without %i in filePattern .

+1
source

Source: https://habr.com/ru/post/1240226/


All Articles