如何在log4j2.02中以编程方式配置Logger? [英] How to configure Logger Programmatically in log4j2.02?
问题描述
我想使用log4j 而不用任何配置文件。
我要做的是:
I want to use log4j without any configure file. What I wan to do is something as:
logger = (Logger) LogManager.getLogger(this.getClass());
String pattern = "[%level] %m%n";
//do something to make this logger output to an local file "/xxx/yyy/zzz.log"
我找到了这个答案:以编程方式配置Log4j记录器。
但 Logger#addAppender
的文档说:
此方法不通过公共API公开,主要用于单元测试。
But the docs of Logger#addAppender
says:
This method is not exposed through the public API and is used primarily for unit testing.
我不确定在我的方法中使用此方法是否正确代码或还有其他更好的解决方案来解决我的问题。
I am not sure if it is the right way to use this method in my code or there is other better solution to solve my problem.
推荐答案
官方文档显示了一个示例:以编程方式添加到当前配置
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, config, null, null,null, null);
Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config);
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig = LoggerConfig.createLogger("false", "info", "org.apache.logging.log4j", "true", refs, null, config, null );
loggerConfig.addAppender(appender, null, null);
config.addLogger("org.apache.logging.log4j", loggerConfig);
ctx.updateLoggers();
有这些限制:
- 如果更改配置文件,将重新加载配置,手动更改将丢失。
- 对运行配置的修改要求调用所有方法(addAppender和addLogger)同步。
此解决方案避免使用核心实现 org.apache.logging中的方法。 log4j.core.Logger
,它避免了这样的脏转换:
This solution avoids to use method from the core implementation org.apache.logging.log4j.core.Logger
, and it avoids dirty cast like that :
import org.apache.logging.log4j.Logger;
Logger logger = (Logger) LogManager.getLogger(this.getClass());
((org.apache.logging.log4j.core.Logger) logger).addAppender(...); // Bypassing the public API
这篇关于如何在log4j2.02中以编程方式配置Logger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!