1 package org.apache.commons.jcs3;
2
3 import java.io.StringWriter;
4 import java.util.logging.Handler;
5 import java.util.logging.Level;
6 import java.util.logging.LogRecord;
7 import java.util.logging.Logger;
8
9 import org.apache.commons.jcs3.log.LogManager;
10
11 /*
12 * Licensed to the Apache Software Foundation (ASF) under one
13 * or more contributor license agreements. See the NOTICE file
14 * distributed with this work for additional information
15 * regarding copyright ownership. The ASF licenses this file
16 * to you under the Apache License, Version 2.0 (the
17 * "License"); you may not use this file except in compliance
18 * with the License. You may obtain a copy of the License at
19 *
20 * http://www.apache.org/licenses/LICENSE-2.0
21 *
22 * Unless required by applicable law or agreed to in writing,
23 * software distributed under the License is distributed on an
24 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
25 * KIND, either express or implied. See the License for the
26 * specific language governing permissions and limitations
27 * under the License.
28 */
29
30 /** Utility for testing log messages. */
31 public class TestLogConfigurationUtil
32 {
33 /**
34 * Configures a logger for the given name. This allows us to check the log output.
35 * <p>
36 * @param stringWriter string writer
37 * @param loggerName logger name
38 */
39 public static void configureLogger( final StringWriter stringWriter, final String loggerName )
40 {
41 LogManager.setLogSystem("jul");
42 java.util.logging.LogManager.getLogManager().reset();
43 final Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
44
45 rootLogger.addHandler(new MockLogHandler(stringWriter));
46 rootLogger.setLevel(Level.FINE);
47 }
48
49 private static class MockLogHandler extends Handler
50 {
51 private final StringWriter writer;
52
53 public MockLogHandler(final StringWriter writer)
54 {
55 this.writer = writer;
56 }
57
58 @Override
59 public void publish(final LogRecord record)
60 {
61 final StringBuilder sb = new StringBuilder();
62 sb.append(record.getMillis())
63 .append(" - ")
64 .append(record.getSourceClassName())
65 .append("#")
66 .append(record.getSourceMethodName())
67 .append(" - ")
68 .append(record.getMessage())
69 .append('\n');
70 writer.append(sb.toString());
71 }
72
73 @Override
74 public void flush()
75 {
76 writer.flush();
77 }
78
79 @Override
80 public void close() throws SecurityException
81 {
82 }
83 }
84 }