Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j FileAppender recreating deleted files

I am using Log4j as logging framework in a project I am working on. I have the following situation: Log4j is configured to write the logs into a log file. At some point, this log file is copied to another destination and deleted. Logging framework keeps working, but the logs are not written to the log file because it is deleted. Is there any way to tell Log4j to recreate the file and keep writing the logs into the log file.

Best regards, Rashid

like image 741
rashid.rashidov Avatar asked Aug 24 '12 09:08

rashid.rashidov


1 Answers

I went through the source code of log4j. When a FileAppender/RollingFileAppender is initialized, a FileOutputStream instance is created pointing to the File. A new FileDescriptor object is created to represent this file connection. This is the reason, the other solutions like Monitoring the file through Cron and Creating the File in append method by overriding didn't work for me, because a new file descriptor is assigned to the new file. Log4j Writer still points to the old FileDescriptor.

The solution was to check if the file is present and if not call the activeOptions method present in FileAppender Class.

package org.apache.log4j;

import java.io.File;
import org.apache.log4j.spi.LoggingEvent;

public class ModifiedRollingFileAppender extends RollingFileAppender {

    @Override 
    public void append(LoggingEvent event) {
        checkLogFileExist();
        super.append(event);
    }

    private void checkLogFileExist(){
        File logFile = new File(super.fileName);
        if (!logFile.exists()) {
            this.activateOptions();
        }
    }
}

Finally add this to the log4j.properties file:

log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ModifiedRollingFileAppender
log4j.appender.A1.File=/path/to/file
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss,SSS} %p %c{1}: %m%n

//Skip the below lines for FileAppender
log4j.appender.A1.MaxFileSize=10MB
log4j.appender.A1.MaxBackupIndex=2

Note: I have tested this for log4j 1.2.17

like image 53
Neelesh Sambhajiche Avatar answered Sep 28 '22 05:09

Neelesh Sambhajiche