如何在 Log4j2 中使用编程配置添加 OutputStream?
How Can I Add The OutputStream Using Programmatical Configuration in Log4j2?
知道如何将我的输出流添加到构建配置吗?
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 组件的另一个示例,请参见 this question。
另请检查 Log4j's architecture,它解释了所有这些组件如何协同工作。
知道如何将我的输出流添加到构建配置吗?
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 组件的另一个示例,请参见 this question。
另请检查 Log4j's architecture,它解释了所有这些组件如何协同工作。