001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.net.mock;
015
016import java.util.concurrent.BlockingQueue;
017import java.util.concurrent.LinkedBlockingQueue;
018import java.util.concurrent.TimeUnit;
019import java.util.concurrent.locks.Condition;
020import java.util.concurrent.locks.Lock;
021import java.util.concurrent.locks.ReentrantLock;
022
023import ch.qos.logback.classic.spi.ILoggingEvent;
024import ch.qos.logback.core.AppenderBase;
025
026/**
027 * A mock {@link AppenderBase} with instrumentation for unit testing.
028 *
029 * @author Carl Harris
030 */
031public class MockAppender extends AppenderBase<ILoggingEvent> {
032
033    private final Lock lock = new ReentrantLock();
034    private final Condition appendCondition = lock.newCondition();
035    private final BlockingQueue<ILoggingEvent> events = new LinkedBlockingQueue<ILoggingEvent>();
036
037    @Override
038    protected void append(ILoggingEvent eventObject) {
039        lock.lock();
040        try {
041            events.offer(eventObject);
042            appendCondition.signalAll();
043        } finally {
044            lock.unlock();
045        }
046    }
047
048    public ILoggingEvent awaitAppend(long delay) throws InterruptedException {
049        return events.poll(delay, TimeUnit.MILLISECONDS);
050    }
051
052    public ILoggingEvent getLastEvent() {
053        return events.peek();
054    }
055
056}