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?
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.