There is so much to tell about the Western country in that day that it is hard to know where to start. One thing sets off a hundred others. The problem is to decide which one to tell first.

—JOHN STEINBECK, East of Eden

Manual · Appenders · Writing your own Appender

Writing your own Appender

Writing your own Appender

You can easily write your appender by subclassing AppenderBase. It handles support for filters, status messages and other functionality shared by most appenders. The derived class only needs to implement one method, namely append(Object eventObject).

The CountingConsoleAppender, which we list next, appends a limited number of incoming events on the console. It shuts down after the limit is reached. It uses a PatternLayoutEncoder to format the events and accepts a parameter named limit. Therefore, a few more methods beyond append(Object eventObject) are needed. As shown below, these parameters are handles auto-magically by logback's various configuration mechanisms.

Example 4.: CountingConsoleAppender (logback-examples/​src/main/java/chapters/​appenders/CountingConsoleAppender.​java)
package chapters.appenders;

import java.io.IOException;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;


public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> {
  static int DEFAULT_LIMIT = 10;
  int counter = 0;
  int limit = DEFAULT_LIMIT;
  
  PatternLayoutEncoder encoder;
  
  public void setLimit(int limit) {
    this.limit = limit;
  }

  public int getLimit() {
    return limit;
  }
  
  @Override
  public void start() {
    if (this.encoder == null) {
      addError("No encoder set for the appender named ["+ name +"].");
      return;
    }
    
    try {
      encoder.init(System.out);
    } catch (IOException e) {
    }
    super.start();
  }

  public void append(ILoggingEvent event) {
    if (counter >= limit) {
      return;
    }
    // output the events as formatted by our layout
    try {
      this.encoder.doEncode(event);
    } catch (IOException e) {
    }

    // prepare for next event
    counter++;
  }

  public PatternLayoutEncoder getEncoder() {
    return encoder;
  }

  public void setEncoder(PatternLayoutEncoder encoder) {
    this.encoder = encoder;
  }
}

The start() method checks for the presence of a PatternLayoutEncoder. In case the encoder is not set, the appender fails to start and emits an error message.

This custom appender illustrates two points:

The CountingConsoleAppender can be configured like any other appender. See sample configuration file logback-examples/​src/main/resources/​chapters/appenders/​countingConsole.​xml for an example.