I have the following logging problem with several Java applications using log4j
for logging:
I want log files to be rotated daily, like
log.2010-09-10
log.2010-09-09
log.2010-09-08
log.2010-09-07
log.2010-09-06
log.2010-09-05
log.2010-09-04
But for data security reasons we are not allowed to keep log files for longer than seven days at my company. So the generation of the next next log file log.2010-09-11
should trigger the deletion of log.2010-09-04
. Is it possible to configure such a behaviour with log4j
? If not, do you know another elegant solution for this kind of logging problem?
Use LogManager. resetConfiguration(); to clear the current config and configure it again. Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config).
The Log4j logging settings are stored in the file app_data /conf/server/log4j. properties, where app_data is the application data folder. You can edit this file directly on the server or open it by clicking Settings > Logging. Note: Do not change the name and location of the server log.
I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex
which you can set to limit the number of files. For example:
log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log log4j.appender.R.MaxFileSize=100KB log4j.appender.R.MaxBackupIndex=7 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
You can perform your housekeeping in a separate script which can be cronned to run daily. Something like this:
find /path/to/logs -type f -mtime +7 -exec rm -f {} \;
According to the following post, you can't do this with log4j: Use MaxBackupIndex in DailyRollingFileAppender -log4j
As far as I know, this functionality was supposed to make it into log4j 2.0 but that effort got sidetracked. According to the logback website, logback is the intended successor to log4j so you might consider using that.
There's an API called SLF4J which provides a common API to logging. It will load up the actual logging implementation at runtime so depending on the configuration that you have provided, it might use java.util.log or log4j or logback or any other library capable of providing logging facilities. There'll be a bit of up-front work to go from using log4j directly to using SLF4J but they provide some tools to automate this process. Once you've converted your code to use SLF4J, switching logging backends should simply be a case of changing the config file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With