Java CyclicBuffer-class And Method Code Example


Here is an example of how to use the CyclicBuffer class from the logback library in Java:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.spi.AppenderAttachable;
import ch.qos.logback.core.spi.AppenderAttachableImpl;
import ch.qos.logback.core.util.CyclicBuffer;
import org.slf4j.LoggerFactory;

public class Example {
    static Logger logger = (Logger) LoggerFactory.getLogger(Example.class);

    public static void main(String[] args) {
        CyclicBufferAppender appender = new CyclicBufferAppender();
        appender.setBufferSize(5);
        appender.start();
        logger.addAppender(appender);

        for (int i = 0; i < 10; i++) {
            logger.debug("This is message number " + i);
        }

        CyclicBuffer<ILoggingEvent> buffer = appender.getCyclicBuffer();
        for (int i = 0; i < buffer.length(); i++) {
            ILoggingEvent event = buffer.get(i);
            System.out.println(event.getFormattedMessage());
        }
    }
}

class CyclicBufferAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    AppenderAttachableImpl<ILoggingEvent> aai = new AppenderAttachableImpl<ILoggingEvent>();
    private int bufferSize;
    private CyclicBuffer<ILoggingEvent> buffer;

    public int getBufferSize() {
        return bufferSize;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public CyclicBuffer<ILoggingEvent> getCyclicBuffer() {
        return buffer;
    }

    public void start() {
        buffer = new CyclicBuffer<ILoggingEvent>(bufferSize);
        super.start();
    }

    public void stop() {
        super.stop();
        buffer = null;
    }

    public void append(ILoggingEvent event) {
        buffer.add(event);
    }

    public void addAppender(Appender<ILoggingEvent> newAppender) {
        aai.addAppender(newAppender);
    }

    public void detachAndStopAllAppenders() {
        aai.detachAndStopAllAppenders();
    }
}

This example creates an instance of the CyclicBufferAppender class which extends UnsynchronizedAppenderBase and uses CyclicBuffer to hold recent log events. the size of the buffer is set to 5, and then the logger is adding the appender to it. After that, it logs 10 debug messages through the logger, the buffer will only keep the last 5 messages, which are then printed to the console.

Please note that

  • You should import the relevant classes for logback
  • The above code is just an example and it does not include the full context