• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.testing;
18 
19 import com.google.common.annotations.Beta;
20 
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.logging.Handler;
25 import java.util.logging.LogRecord;
26 
27 /**
28  * Tests may use this to intercept messages that are logged by the code under
29  * test.  Example:
30  * <pre>
31  *   TestLogHandler handler;
32  *
33  *   protected void setUp() throws Exception {
34  *     super.setUp();
35  *     handler = new TestLogHandler();
36  *     SomeClass.logger.addHandler(handler);
37  *     addTearDown(new TearDown() {
38  *       public void tearDown() throws Exception {
39  *         SomeClass.logger.removeHandler(handler);
40  *       }
41  *     });
42  *   }
43  *
44  *   public void test() {
45  *     SomeClass.foo();
46  *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
47  *     assertEquals("some message", firstRecord.getMessage());
48  *   }
49  * </pre>
50  *
51  * @author Kevin Bourrillion
52  * @since 10.0
53  */
54 @Beta
55 public class TestLogHandler extends Handler {
56   /** We will keep a private list of all logged records */
57   private final List<LogRecord> list =
58       Collections.synchronizedList(new ArrayList<LogRecord>());
59 
60   /**
61    * Adds the most recently logged record to our list.
62    */
63   @Override
publish(LogRecord record)64   public void publish(LogRecord record) {
65     list.add(record);
66   }
67 
68   @Override
flush()69   public void flush() { }
70 
71   @Override
close()72   public void close() { }
73 
clear()74   public void clear() {
75     list.clear();
76   }
77 
78   /**
79    * Fetch the list of logged records
80    * @return unmodifiable LogRecord list of all logged records
81    */
getStoredLogRecords()82   public List<LogRecord> getStoredLogRecords() {
83     List<LogRecord> result = new ArrayList<LogRecord>(list);
84     return Collections.unmodifiableList(result);
85   }
86 }
87