Rotating File Handler

In this post under logging, I will show how to create a rotating file handler.

A rotating file handler create a set of files, with each file having a count in the file name indicating the total number of files created. Each file has a size limit, which when reached a new file is created or existing file is overriden. They will be a limit on the number of files that can be created. Once the limit is reached, new log messages are inserted into existing files in order.

We are create a rotating file handler using the below two constructor

public FileHandler(String pattern, int limit, int count) throws IOException, SecurityException

public FileHandler(String pattern, int limit, int count, boolean append) throws IOException, SecurityException

    pattern - the pattern for naming the output file
    limit - the maximum number of bytes to write to any one file
    count - the number of files to use
    append - specifies append mode

Below is an example of how to create a rotating file handler

Main Class

1  package logging;
3  import;
4  import java.util.logging.FileHandler;
5  import java.util.logging.Level;
6  import java.util.logging.Logger;
8  public class LoggingDemo9 {
9   public static void main(String[] args) throws IOException {
10      Logger logger = Logger.getLogger("logger");
11      FileHandler fileHandler = null;
12      try {
13          fileHandler = new FileHandler("java.log", 300000, 3, true);
14          fileHandler.setLevel(Level.INFO);
16          logger.addHandler(fileHandler);
17          for(int i = 0; i < 2000; i++) {
18    "Log message: " + i);
19          }
21          logger.removeHandler(fileHandler);
22      } finally {
23          fileHandler.close();
24      }
25  }
26 }

At line 13 we create an instance of FileHandler with file name as “java.log”, with limit on size of each file to 300KB, and maximum number of files to created will be 3.

So when the example is run it creates three files with below names, if the limit of java.log.2 reaches 300KB, the existing file java.log.0 is overridden with new log messages, since the limit on the number of files to be created is 3.

Check these products on Amazon

Leave a Reply