简体   繁体   English

每次在log4j中重写到相同的日志文件

[英]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. 到目前为止,我一直尝试删除该文件,但是由于FileDescriptor未发布,因此并未删除。 So I added following code in stop() function 所以我在stop()函数中添加了以下代码

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]. log4j:ERROR尝试附加到名为[null]的封闭附加程序。

Please somebody help me in solving this. 请有人帮我解决这个问题。

The error message indicates that you have to remove the appender after closing it. 该错误信息表明您必须在关闭附加程序后将其删除。 It seems log4j will not do this automatically. 看来log4j不会自动执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM