0

In my java-server I use the java.util.logging framework to log the state of my program. To avoid a too large log file I use this Filehandler constructor:

//import java.util.logging.FileHandler;
//import java.util.logging.Logger;

FileHandler fileLog = new FileHandler("log%g.txt", 10 * 1024*1014, 2, false);
logger.addHandler(fileLog);

In my understanding the logger writes now into log0.txt until the file size is bigger than 10MB. Then he changes to log1.txt. When file size is bigger than 10 MB he changes back to log0.txt. Is this right?

So in this case the old log files will be overwritten. To avoid this I want to call a Methode (in which I send a email to the administrator), when the logger changes the output file.

void callOnOutputfileChanged() {
  sendEmailToAdmin();
}

Do you have an idea how to react on this event?

tv31
  • 55
  • 6
morgelo
  • 136
  • 15
  • Looking at the FileHandler doc, it doesn't offer any way of registering listeners for this type of event. If you want to prevent overwriting, why not set no limit? It's unlikely you'll run out of disk space. – Adrian Leonhard Feb 21 '15 at 11:31
  • This problem is part of a university project and my mentor recommended to check for a growing logfile. So of course I can use the code above with a high limit and than I don't mind if the first file is overwritten. Or what do you think - is it better to use log4j? Maybe I can do there some equivalent function? – morgelo Feb 21 '15 at 12:07

1 Answers1

1

When file size is bigger than 10 MB he changes back to log0.txt. Is this right?

In the normal case yes. If the FileHandler can't aquire a lock on the file then there are some other rules that take place.

So in this case the old log files will be overwritten. To avoid this I want to call a Methode (in which I send a email to the administrator), when the logger changes the output file.

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 ListeningFileHandler extends FileHandler {

        public ListeningFileHandler() throws IOException {
            super();
        }

        @Override
        protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
            super.setOutputStream(out);
            if (Level.OFF.equals(super.getLevel())) { //Rotating...
                sendEmailToAdmin();
            }
        }

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

If you want to prevent rotation then you have to change your goals. You either have to leave the limit and increase the count or lower the count and increase the limit.

jmehrens
  • 10,580
  • 1
  • 38
  • 47