All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.neuland.assertj.logging.Log4j12LogEventCaptureAppender Maven / Gradle / Ivy

There is a newer version: 0.4.0
Show newest version
package de.neuland.assertj.logging;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;

import java.util.ArrayList;
import java.util.List;


public class Log4j12LogEventCaptureAppender extends AppenderSkeleton implements LogEventCaptureAppender {
    private final List logEvents = new ArrayList<>();

    @Override
    public List getLogEvents() {
        return logEvents;
    }

    @Override
    public void append(LoggingEvent event) {
        logEvents.add(new LogEvent(logLevel(event),
                                   message(event),
                                   throwable(event)));
    }

    @Override
    public void close() {
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    private LogLevel logLevel(LoggingEvent event) {
        Level level = event.getLevel();
        if (Level.ERROR.equals(level)) {
            return LogLevel.ERROR;
        }
        if (Level.WARN.equals(level)) {
            return LogLevel.WARNING;
        }
        if (Level.INFO.equals(level)) {
            return LogLevel.INFO;
        }
        return LogLevel.IGNORED;
    }

    private String message(LoggingEvent event) {
        return event.getRenderedMessage();
    }

    private Throwable throwable(LoggingEvent event) {
        return event.getThrowableInformation() != null
            ? event.getThrowableInformation().getThrowable()
            : null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy