Suzan Cioc
Suzan Cioc

Reputation: 30127

Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER>

I wish to write custom appender on the basis of OutputStreamAppender. I wrote the following class

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();
            }
        });
    }
}

then I wrote the following runner:

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");
    }
}

finally I wrote the following 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>

and got the following output:

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

it indicates that appender is instantiated. But absence of exceptions mean it is never called.

Probably this is related with error message which I don't understand: "LOGBACK: No context given for tests.MyAppender[null]"

What is it mean and how to fix?

Upvotes: 3

Views: 10137

Answers (2)

Suzan Cioc
Suzan Cioc

Reputation: 30127

Sorry, this was my fault: I forgot to set my custom appender in <root> tag.

Upvotes: 0

Karthik Prasad
Karthik Prasad

Reputation: 10034

How would you set the filename where you want to write there are lots of other issues when you extend OutputStreamAppender I would rather extend FileAppender(which intern extension of outputsteamappender) and override write method to perfrom custom task.

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();
  }

}

Upvotes: 0

Related Questions