How to Setup Rolling Logs with Log4J

  • 7011121
  • 27-Apr-2012
  • 19-Oct-2012

Resolution

Setup Rolling Logs with Log4J:
It is recommended to consider using log4J output as opposed to system.out, this allows for finer grain control of logging and allows logging performance to be controlled.

In the example below, the backup index of 10 will determine how many files are created.  In this case, you'll get 10 files for backups plus one for the active log.  The active log will be iiq_training_rolling.log and the backups will be iiq_training_rolling.log.1 to iiq_training_rolling.log.10.  

Proper rolling log setup using log4j properties file:  

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=c:/spdemo/iiq_rolling.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %5p %t %c{4}:%L - %m%n
log4j.appender.file.MaxFileSize=5000KB
log4j.appender.file.MaxBackupIndex=10

Customization options: 

Log file location: 
Change the line "log4j.appender.file.File=" to point to where you'd like the log file to go (this way you can move it to a different partition if needed for space reasons.) 

When to roll the logs: 
Change the line "log4j.appender.file.MaxFileSize" to something more or less than 5000KB if you want the logs to roll at an interval other than 5MB. 

Number of rolling backups: 
Change the line "log4j.appender.file.MaxBackupIndex" to something other than 10 if you want more or less than 10 rolling backup files.