user3540481
user3540481

Reputation: 221

Rewriting to same log file each time in log4j

I have a product using which I run my application(which I have written). It is a multithreaded application which access one single log file. I am facing the problem that each time I start my application log file is getting appended. Only when I restart the product then fresh log file is created. But I want each time my application is running I want only fresh content in my log file.

Below is the code.

//Log4j initialization
public void initLog4j() throws MyException {

    if (logfile != null ){
        myLog4j = Logger.getLogger("MY_LOG");           
        try {
            appender = new FileAppender(new PatternLayout("%m%n"),logfile.getAbsolutePath(),false);
            appender.setAppend(false);
            myLog4j.addAppender(appender);
            myLog4j.setLevel((Level) Level.DEBUG);
        } catch (IOException e) {
            throw new MyException(104, logfile.getAbsolutePath());
        }           

    }

//Stopping to write to log4j
public void stop() {        
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");        
    writeToLog4j(INFO,new StringBuilder(name).append(" stop: ").append(dateFormat.format(new Date())).toString(),true);
}

What I tried till now is I tried deleting the file but it was not deleting as FileDescriptor was not released. So I added following code in stop() function

if(null != appender) {
        appender.close();
    }

After this new File is getting generated or existing file is overwritten. But each time my application is run I am having below message each time I try writing to logfile

log4j:ERROR Attempted to append to closed appender named [null].

Please somebody help me in solving this.

Upvotes: 0

Views: 1061

Answers (1)

Fildor
Fildor

Reputation: 16104

The error message indicates that you have to remove the appender after closing it. It seems log4j will not do this automatically.

Upvotes: 1

Related Questions