0

My log file creation code is as follows:

public static final int FILE_SIZE = 512 * 1024;

public static void setup() throws SecurityException, IOException {
    Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    logger.setLevel(Level.INFO);
    try {
        FileHandler handler = new FileHandler("/data/mcmlog", FILE_SIZE, 10, true);
        handler.setFormatter(new LogFormatter());
        logger.addHandler(handler);
        logger.setUseParentHandlers(false);
    } catch (IOException e) {
        logger.warning("Failed to initialize logger handler.");
    }
}

It creates log file from mcmlog.0 to mcmlog.9 in cyclic manner. I have to zip these log files when mcmlog.9 is about to be overwritten by mcmlog.8 . How to find when mcmlog.9 is about to be overwritten.

Neha
  • 1

1 Answers1

0

How to find when mcmlog.9 is about to be overwritten.

Currently the only way to listen for when the FileHandler rotates is to extend FileHandler and override the protected void setOutputStream(OutputStream) method. FileHandler level is set to OFF during the rotation.

Here is an example class:

    public class ZipFileHandler extends FileHandler {
        private long rotated;
        private final long count;

        public ZipFileHandler(String p, long size, long count, boolean append) throws IOException {
            super(p, size, count, append);
            this.count = count;
        }

        @Override
        protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
            try {
                if (Level.OFF.equals(super.getLevel())) { //Rotating...
                    if (rotated++ != 0 && rotated % count == 0) {
                        zipFiles();
                    }
                }
            } finally {
                super.setOutputStream(out);
            }
        }

        private void zipFiles() {
            //...
        }
    }

You may run into a problem with file locking using that solution. In which case you should build out a proxy handler to deal with opening and closing the FileHandler.

jmehrens
  • 10,580
  • 1
  • 38
  • 47