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 java.util.ArrayList;
021import java.util.Collections;
022import java.util.List;
023import java.util.logging.Handler;
024import java.util.logging.LogRecord;
025import javax.annotation.CheckForNull;
026
027/**
028 * Tests may use this to intercept messages that are logged by the code under test. Example:
029 *
030 * <pre>
031 *   TestLogHandler handler;
032 *
033 *   protected void setUp() throws Exception {
034 *     super.setUp();
035 *     handler = new TestLogHandler();
036 *     SomeClass.logger.addHandler(handler);
037 *     addTearDown(new TearDown() {
038 *       public void tearDown() throws Exception {
039 *         SomeClass.logger.removeHandler(handler);
040 *       }
041 *     });
042 *   }
043 *
044 *   public void test() {
045 *     SomeClass.foo();
046 *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
047 *     assertEquals("some message", firstRecord.getMessage());
048 *   }
049 * </pre>
050 *
051 * @author Kevin Bourrillion
052 * @since 10.0
053 */
054@GwtCompatible
055public class TestLogHandler extends Handler {
056  /** We will keep a private list of all logged records */
057  private final List<LogRecord> list = new ArrayList<>();
058
059  /** Adds the most recently logged record to our list. */
060  @Override
061  public synchronized void publish(@CheckForNull LogRecord record) {
062    list.add(record);
063  }
064
065  @Override
066  public void flush() {}
067
068  @Override
069  public void close() {}
070
071  public synchronized void clear() {
072    list.clear();
073  }
074
075  /** Returns a snapshot of the logged records. */
076  /*
077   * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
078   * getOnlyRecordLogged(), getAndClearLogRecords()...)
079   *
080   * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
081   * an ImmutableList)
082   */
083  public synchronized List<LogRecord> getStoredLogRecords() {
084    List<LogRecord> result = new ArrayList<>(list);
085    return Collections.unmodifiableList(result);
086  }
087}