/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.technicalconnector.tests.log4j;

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

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


/**
 * Custom log4j appender in order to verify the log event.
 *
 * @author EH053
 */
public class TestAppender extends AppenderSkeleton {

    private final List<LoggingEvent> events = new ArrayList<LoggingEvent>();

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

    @Override
    protected void append(final LoggingEvent loggingEvent) {
        events.add(loggingEvent);
    }

    @Override
    public void close() {
    }

    public List<LoggingEvent> getLogEvents() {
        return new ArrayList<LoggingEvent>(events);
    }

    public List<LoggingEvent> getLogEvents(Class logger) {
        List<LoggingEvent> result = new ArrayList<LoggingEvent>();
        for (LoggingEvent event : events) {
            if (event.getLoggerName().equals(logger.getName())) {
                result.add(event);
            }
        }
        return result;
    }

    public LoggingEvent getLastLogEvent(Class logger) {
        List<LoggingEvent> logEvents = getLogEvents(logger);
        if (!logEvents.isEmpty()) {
            return logEvents.get(logEvents.size() - 1);
        }
        return null;
    }
}