LogBack ロガーの場合、ByteArrayOutputStream に書き込むOutputStreamAppenderをプログラムで作成しようとしています。これが私がこれまでに持っているものです:
// Destination stream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Get LoggerContext from SLF4J
LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
// Encoder
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern("%d{HH:mm:ss} %-5level %logger{36} - %msg%n");
encoder.start();
// OutputStreamAppender
OutputStreamAppender<ILoggingEvent> appender= new OutputStreamAppender<>();
appender.setName( "OutputStream Appender" );
appender.setContext(context);
appender.setOutputStream(printStream);
appender.setEncoder(encoder);
appender.start();
Logger log = context.getLogger(this.getClass());
log.addAppender(appender);
log.info( "text from logger");
// Output to stdout logback status
StatusPrinter.print(context);
私が読んだすべてに基づいて、これは正しいはずです。Logger からの何もストリームに書き込まれず、OutputStreamAppender は からの出力に従って正しく初期化できませんStatusPrinter
。
15:26:30,330 |-WARN in ch.qos.logback.core.OutputStreamAppender[OutputStream Appender] - Encoder has not been set. Cannot invoke its init method.
15:26:30,335 |-ERROR in ch.qos.logback.core.OutputStreamAppender[OutputStream Appender] - Appender [OutputStream Appender] failed to append. java.lang.NullPointerException
at java.lang.NullPointerException
at at ch.qos.logback.core.encoder.LayoutWrappingEncoder.doEncode(LayoutWrappingEncoder.java:135)
at at ch.qos.logback.core.OutputStreamAppender.writeOut(OutputStreamAppender.java:188)
at at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:212)
at at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:103)
at at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:88)
at at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:48)
at at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:272)
at at ch.qos.logback.classic.Logger.callAppenders(Logger.java:259)
at at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:441)
at at ch.qos.logback.classic.Logger.filterAndLog_0_Or3Plus(Logger.java:395)
at at ch.qos.logback.classic.Logger.info(Logger.java:599)
の警告と NPE に困惑していますLayoutWrappingEncoder.doEncode(LayoutWrappingEncoder)
。アペンダーにエンコーダーを設定しています。