View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.net.mock;
15  
16  import java.util.concurrent.BlockingQueue;
17  import java.util.concurrent.LinkedBlockingQueue;
18  import java.util.concurrent.TimeUnit;
19  import java.util.concurrent.locks.Condition;
20  import java.util.concurrent.locks.Lock;
21  import java.util.concurrent.locks.ReentrantLock;
22  
23  import ch.qos.logback.classic.spi.ILoggingEvent;
24  import ch.qos.logback.core.AppenderBase;
25  
26  /**
27   * A mock {@link AppenderBase} with instrumentation for unit testing.
28   *
29   * @author Carl Harris
30   */
31  public class MockAppender extends AppenderBase<ILoggingEvent> {
32  
33      private final Lock lock = new ReentrantLock();
34      private final Condition appendCondition = lock.newCondition();
35      private final BlockingQueue<ILoggingEvent> events = new LinkedBlockingQueue<ILoggingEvent>();
36  
37      @Override
38      protected void append(ILoggingEvent eventObject) {
39          lock.lock();
40          try {
41              events.offer(eventObject);
42              appendCondition.signalAll();
43          } finally {
44              lock.unlock();
45          }
46      }
47  
48      public ILoggingEvent awaitAppend(long delay) throws InterruptedException {
49          return events.poll(delay, TimeUnit.MILLISECONDS);
50      }
51  
52      public ILoggingEvent getLastEvent() {
53          return events.peek();
54      }
55  
56  }