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
019
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.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  /** 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(@Nullable LogRecord record) {
064    if (record != null) {
065      list.add(record);
066    }
067  }
068
069  @Override
070  public void flush() {}
071
072  @Override
073  public void close() {}
074
075  public synchronized void clear() {
076    list.clear();
077  }
078
079  /** Returns a snapshot of the logged records. */
080  /*
081   * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
082   * getOnlyRecordLogged(), getAndClearLogRecords()...)
083   *
084   * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
085   * an ImmutableList)
086   */
087  public synchronized List<LogRecord> getStoredLogRecords() {
088    List<LogRecord> result = new ArrayList<>(list);
089    return Collections.unmodifiableList(result);
090  }
091}