001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.testing;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.concurrent.GuardedBy;
021import java.util.ArrayList;
022import java.util.Collections;
023import java.util.List;
024import java.util.logging.Handler;
025import java.util.logging.LogRecord;
026import org.checkerframework.checker.nullness.qual.Nullable;
027
028/**
029 * Tests may use this to intercept messages that are logged by the code under test. Example:
030 *
031 * <pre>
032 *   TestLogHandler handler;
033 *
034 *   protected void setUp() throws Exception {
035 *     super.setUp();
036 *     handler = new TestLogHandler();
037 *     SomeClass.logger.addHandler(handler);
038 *     addTearDown(new TearDown() {
039 *       public void tearDown() throws Exception {
040 *         SomeClass.logger.removeHandler(handler);
041 *       }
042 *     });
043 *   }
044 *
045 *   public void test() {
046 *     SomeClass.foo();
047 *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
048 *     assertEquals("some message", firstRecord.getMessage());
049 *   }
050 * </pre>
051 *
052 * @author Kevin Bourrillion
053 * @since 10.0
054 */
055@GwtCompatible
056@ElementTypesAreNonnullByDefault
057public class TestLogHandler extends Handler {
058  private final Object lock = new Object();
059
060  /** We will keep a private list of all logged records */
061  @GuardedBy("lock")
062  private final List<LogRecord> list = new ArrayList<>();
063
064  /** Adds the most recently logged record to our list. */
065  @Override
066  public void publish(@Nullable LogRecord record) {
067    synchronized (lock) {
068      if (record != null) {
069        list.add(record);
070      }
071    }
072  }
073
074  @Override
075  public void flush() {}
076
077  @Override
078  public void close() {}
079
080  public void clear() {
081    synchronized (lock) {
082      list.clear();
083    }
084  }
085
086  /** Returns a snapshot of the logged records. */
087  /*
088   * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
089   * getOnlyRecordLogged(), getAndClearLogRecords()...)
090   *
091   * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
092   * an ImmutableList)
093   */
094  public List<LogRecord> getStoredLogRecords() {
095    synchronized (lock) {
096      List<LogRecord> result = new ArrayList<>(list);
097      return Collections.unmodifiableList(result);
098    }
099  }
100}