In the previous post of the Log4j tutorial series, I wrote about the very basics of adding Log4j logging to your project. In this post, I’ll explain how to create a File Appender to log messages into a file, instead of console.
Log4j File Appenders - example for Logging messages to a file:
In most cases, either Rolling File Appender or Daily Rolling File Appender classes are used in production scenarios for logging messages into a file. A Rolling File Appender will send all the log messages to the configured file, until the file reaches a certain size. Once the log file reaches a maximum size, the current file will be backed up and a new log file will be created (thus the name Rolling File Appender). The Daily Rolling File Appender is also similar to Rolling File Appender except that the rolling happens at given frequency. Below is an example for using RollingFileAppender
- Add Log4j logging support to your project. Read this article for how to do it.
- In your log4j.properties file, add below lines.
- As you can see from the above log4j configuration, we are creating a new log4j appender in the name of rollingFile and setting it’s options. I guess most of the options are self explanatory. The MaxBackupIndex tells the log4j to keep a maximum of 2 backup files for the log mylog.log. If the log file is exceeding the MaximumFileSize, then the contents will be copied to a backup file and the logging will be added to a new empty mylog.log file. From the above configuration, there can be a maximum of 2 backup files can be created.
- Next we need to direct our logs to go into this log4j appender.
- That’s it. From now on, when you log something from your Java class, the log message will go into the mylog.log file.
Previous: Adding Log4j logging to your project.