With this policy, it's mandatory to specify a template for the path of the log file that contains a time-related placeholder. To do this, we can use the TimeBasedRollingPolicy. In a web application, for instance, we may want to have all the log messages issued in one day in the same log file. In other scenarios, we may want to configure Log4j to roll the files based on the date and time of the log messages, instead of the size of the file. These two concepts are key to rolling log files, and other libraries use them more or less explicitly as well. The triggering policy describes when a roll should occur, while the rolling policy describes how the rolling should be carried out. The appenders contained in this artifact offer lots of options to fine tune the log rolling, and they introduce the distinct concepts of triggering policy and rolling policy. To do this, we'll use other more powerful, flexible, and configurable Log4j appenders that are shipped in a dedicated package, called apache-log4j-extras. Now let's see if we can devise a setup better suited to a production environment, where losing log messages isn't considered the best approach. When we check the first line of app.log.2, it contains the message related to the 700th iteration, meaning all previous log messages were lost: 10:28:34 INFO This is the 700 time I say 'Hello World'. So we solved one of the original problems because now we can set up a limit on the size of the produced log files. This rolling process was repeated several times during the run, but since we configured our appender to keep two rolled files at most, there isn't a file called app.log.3. This time, app.log.1 was moved to app.log.2, making room for another new empty app.log.
Then, after the new app.log exceeded the 5KB limit, this rolling process was repeated. When the file size exceeded the 5KB limit, Log4j moved app.log to app.log.1, created a new empty app.log, and continued writing new log messages to app.log. So what happened? Log4j started writing to the app.log file. When we run our sample application, we obtain the following files: 10:28 138 app.log We also instructed Log4j to keep a maximum of two rolled log files using the MaxBackupIndex parameter. Here we configured Log4j to roll the log file when its size reaches 5KB using the MaxFileSize parameter.
Let's look at the configuration for a rolling file appender in Log4j that rolls based on file size: In Log4j, as in other logging libraries, file rolling is delegated to the appender.