如何在Log4j2中使用程序配置添加OutputStream



知道如何将输出流添加到构建配置中吗?

ConfigurationBuilder<BuiltConfiguration> builder = 
ConfigurationBuilderFactory.newConfigurationBuilder();

AppenderComponentBuilder osAppender = builder.newAppender("os", "OutputStream");
osAppender.addAttribute("target", myStream);
builder.add(osAppender);

BuiltConfiguration config = builder.build();
Configurator.initialize(config);

这是我收到的错误消息:

2022-01-27 15:04:41,203 main ERROR OutputStream contains an invalid element or attribute "target"
2022-01-27 15:04:41,227 main ERROR Could not create plugin of type class org.apache.logging.log4j.core.appender.OutputStreamAppender for element OutputStream: java.lang.NullPointerException java.lang.NullPointerException
at org.apache.logging.log4j.core.appender.OutputStreamAppender.getManager(OutputStreamAppender.java:159)

感谢

ConfigurationBuilder API不允许您设置无法序列化为String的属性。因此,您需要直接使用OutputSreamAppender的构建器:

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final Appender appender = OutputStreamAppender.newBuilder()//
.setTarget(myStream)
.setConfiguration(ctx.getConfiguration())
.build();
config.addLoggerAppender(ctx.getRootLogger(), appender);

有关ConfigurationBuilder API与Log4j组件的直接实例化的另一个示例,请参阅此问题。

还可以查看Log4j的体系结构,它解释了所有这些组件是如何协同工作的。

相关内容

  • 没有找到相关文章

最新更新