Log4j:在运行时创建/修改appender,重新创建日志文件而不附加 [英] Log4j : Creating/Modifying appenders at runtime, log file recreated and not appended

查看:97
本文介绍了Log4j:在运行时创建/修改appender,重新创建日志文件而不附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为特定方法调用MyMethod()创建和启用appender,其日志输出应该转到logFilePath中的文件。

I want to create and enable an appender for a particular method call MyMethod(), whose log output is supposed to go to a file present at "logFilePath".

我不想在xml配置文件中包含这个appender,所以我想在运行时创建它。

I do not want to include this appender in the xml configuration file, so I thought to create it at run time.

首先,我尝试在运行时修改记录器属性,然后调用activateOptions,例如。将level设置为DEBUG并在finally块中将其设置为Off,以便仅在方法使用时记录输出。这不起作用。

First, I tried to modify the logger properties at runtime and then calling activateOptions, eg. setting level to DEBUG before and setting it to Off in the finally block, so that output is logged only while the method is in use. That didn't work.

我的问题是,appender每次都会重新创建一个文件,而不会附加到同一个文件中。这是因为setAppend是真的。

My problem here is that appender recreates a file everytime, and does not append to the same file. This is inspite of setAppend being true.

我对log4j不太熟悉,所以请随意提出另一种方法。
以下是解释我正在尝试的示例代码。

I am not very familiar with log4j, so please feel free to suggest an alternative approach. The following is sample code to explain what I am trying.

private static FileAppender createNewAppender(String logFilePath) {
    FileAppender appender = new FileAppender();
    appender.setName("MyFileAppender");
    appender.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
    appender.setFile(logFilePath);
    appender.setAppend(true);
    appender.setThreshold(Level.INFO);
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);
    return appender;
}

private static void removeAppender() {
    Logger.getRootLogger().removeAppender(fileAppender) ; // ("MyFileAppender");
}

我通过以下方式调用上述方法:

I call the above methods in the following way:

private static FileAppender fileAppender = null;

private static void myMethod(String logFilePath) {        
    try {
        fileAppender = createNewAppender();
        someOperation();
    }
    finally {
        removeAppender();
        fileAppender=null; 
    }
}


推荐答案

非常只需创建一个方法并添加此

very easy just create a method and add this

String targetLog="where ever you want your log"

FileAppender apndr = new FileAppender(new PatternLayout("%d %-5p [%c{1}] %m%n"),targetLog,true);    
logger.addAppender(apndr);
logger.setLevel((Level) Level.ALL);

然后在您需要记录的任何方法中执行此操作:
logger.error(你的错误在这里);

then in any method you need to log just do this: logger.error("your error here");

这篇关于Log4j:在运行时创建/修改appender,重新创建日志文件而不附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆