[英]How to separate a Log4j configuration?
我有一个程序,它有一个用 XML 编写的 log4j 配置。 我正在尝试修改原始应用程序,并尝试改进以前的记录器配置。
由于我无法修改 xml 文件本身,我希望能够通过ConfigurationBuilderFactory
生成新ConfigurationBuilderFactory
,并将其与其他配置一起使用。 唯一的问题是,我无法做到这一点。 它似乎不想与两者一起工作。
我能做什么?
以下是我的代码,大大简化了:
/**
* Internally uses {@link org.apache.logging.log4j.Logger}
*/
public final class MyLogger {
private static final LoggerContext context;
static {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
{
builder.setStatusLevel(WARN);
AppenderComponentBuilder console = builder.newAppender("SysOut", "Console");
console.addAttribute(...);
console.add(builder.newLayout(...).addAttribute(...));
builder.add(console);
// ... more configuration below
}
context = Configurator.initialize(builder.build()); // only works if no previous config exists, but will not replace an old config
}
}
// later on...
context.getLogger("MyLogger"); // uses the xml config, not the one written above
我认为您可以创建自己的log4j.xml 。 您必须确保您的 XML 将加载到您的程序中。 因此,只需在包含其他 XML 的资源之前在Java 类路径中定义包含您的 XML 的资源。
要以编程方式使用 ConfigurationBuilder API 创建记录器,您可以参考以下代码。
它在 log4j2 环境中创建了一个记录器,并添加了一些布局和附加器定义:
public class Log4j2Logger {
int counter = 0;
LoggerContext ctx;
Configuration config;
Logger logger;
String loggerName = "testLogger";
String appenderName = "myAppender";
static String testMessage = "This is a Test Message";
public void log() {
final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
final LoggerComponentBuilder loggerComp = builder.newLogger(loggerName, Level.ALL).addAttribute("additivity",
false);
builder.add(loggerComp);
config = builder.build();
ctx = Configurator.initialize(config);
config = ctx.getConfiguration();
ctx.start(config);
ctx.updateLoggers(config);
// To create/add the logger of the configuration specified above we can use the
// getLogger(..) method
logger = ctx.getLogger(loggerName);
// Now we need to attach an appender to the logger so that our messages could be
// logged
logger.addAppender(addConsoleAppender(ctx.getConfiguration(), appenderName));
while (counter < 10) {
logger.error(testMessage + counter);
counter++;
}
}
private Appender addConsoleAppender(Configuration config, String appenderName) {
Appender consoleAppender = ConsoleAppender.newBuilder().setConfiguration(config).setName(appenderName)
.withImmediateFlush(true).build();
consoleAppender.start();
return consoleAppender;
}
}
对于测试,您可以在任何测试类中进行以下操作:
Log4j2Logger testLogger = new Log4j2Logger();
testLogger.log();
此 API 可帮助您以强大的方式处理日志。
你可以 :
PS:我用的是log4j2 2.12.1版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.