自定义OutputStreamAppender未运行:LOGBACK:没有给出<myappender> </myappender>的上下文

时间:2015-03-31 16:52:01

标签: java logging logback appender

我希望在OutputStreamAppender的基础上编写自定义appender。我写了下面的课程

package tests;

import java.io.IOException;
import java.io.OutputStream;

import ch.qos.logback.core.OutputStreamAppender;

public class MyAppender<E> extends OutputStreamAppender<E> {
    public MyAppender() {

        System.out.println("MyAppender created");

        setOutputStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                throw new UnsupportedOperationException();
            }
        });
    }
}

然后我写了下面的跑步者:

package tests;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

public class Runner {

    private static final Logger log = (Logger) LoggerFactory.getLogger(Runner.class);


    public static void main(String[] args) {

        //log.addAppender(new MyAppender<ILoggingEvent>());

        log.info("Hello world");
    }
}

最后我写了以下logback.xml

<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="MYAPPENDER" class="tests.MyAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n</pattern>
        </encoder>
    </appender>



    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

并获得以下输出:

MyAppender created
LOGBACK: No context given for tests.MyAppender[null]
20:45:29.957 [main] INFO  Runner - Hello world

表示appender已实例化。但没有例外意味着它永远不会被称为。

可能这与我不理解的错误消息有关:“LOGBACK:没有为tests.MyAppender [null]提供上下文”

是什么意思以及如何解决?

2 个答案:

答案 0 :(得分:0)

如何设置文件名你想要写的地方当你扩展OutputStreamAppender时还有很多其他问题我宁愿扩展FileAppender(outputsteamappender的内部扩展)和覆盖写执行自定义任务的方法。

public class MyAppender<E> extends FileAppender<E> {

 @Override
  protected void writeOut(E event) throws IOException {
    /**if (prudent) {
      safeWrite(event);
    } else {
      super.writeOut(event);
    } */
    throw new UnsupportedOperationException();
  }

}

答案 1 :(得分:0)

抱歉,这是我的错:我忘了在<root>标记中设置我的自定义附加程序。