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.Beta;
020import com.google.common.annotations.GwtCompatible;
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.compatqual.NullableDecl;
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@Beta
056@GwtCompatible
057public class TestLogHandler extends Handler {
058  /** We will keep a private list of all logged records */
059  private final List<LogRecord> list = new ArrayList<>();
060
061  /** Adds the most recently logged record to our list. */
062  @Override
063  public synchronized void publish(@NullableDecl LogRecord record) {
064    list.add(record);
065  }
066
067  @Override
068  public void flush() {}
069
070  @Override
071  public void close() {}
072
073  public synchronized void clear() {
074    list.clear();
075  }
076
077  /** Returns a snapshot of the logged records. */
078  /*
079   * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
080   * getOnlyRecordLogged(), getAndClearLogRecords()...)
081   *
082   * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
083   * an ImmutableList)
084   */
085  public synchronized List<LogRecord> getStoredLogRecords() {
086    List<LogRecord> result = new ArrayList<>(list);
087    return Collections.unmodifiableList(result);
088  }
089}