The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.logging  [20 examples] > File Size  [2 examples]

e402. Limiting the Size of a Log by Using a Rotating Sequence of Files

The example e401 Limiting the Size of a Log File shows how to limit the log file size by automatically emptying it when it reaches the limit. However, this approach has the disadvantage of discarding useful information even though the file size might be well within the limit. The FileHandler allows a more effective approach by allowing you to use a sequence of files to hold the log information. When a file fills up, the oldest file is emptied and logging resumes in that file.

More specifically, if there are N log files in the sequence, records are always dumped into logfile0. When logfile0 is filled, logfileN-2 is renamed to logfileN, logfileN-3 is renamed to logfileN-2, etc. Finally, logfile0 is renamed logfile1. A new logfile0 is created and logging resumes in the new logfile0. To read the log records in chronological order, you need to process the files from logfileN-1 to logfile0.

The logfile number is called the generation number and ranges from 0 to the number of logfiles - 1. When specifying the filename pattern to use for the logfiles, you need to include the location of the generation number using the %g placeholder. For example, using a filename pattern of my%g.log with three log files will result in the files my0.log, my1.log, and my2.log.

    try {
        // Create a file handler that uses 3 logfiles, each with a limit of 1Mbyte
        String pattern = "my%g.log";
        int limit = 1000000; // 1 Mb
        int numLogFiles = 3;
        FileHandler fh = new FileHandler(pattern, limit, numLogFiles);
    
        // Add to logger
        Logger logger = Logger.getLogger("com.mycompany");
        logger.addHandler(fh);
    } catch (IOException e) {
    }

 Related Examples
e401. Limiting the Size of a Log File

See also: Configuration    Formatters    Levels   


© 2002 Addison-Wesley.