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

6yt4nkrj  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(152)

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

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)

谢谢

nwlls2ji

nwlls2ji1#

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组件的直接示例化的另一个示例,请参见this question
另请查看Log4j's architecture,它解释了所有这些组件如何协同工作。

相关问题