]> WPIA git - gigi.git/blob - lib/jetty/org/eclipse/jetty/util/log/StacklessLogging.java
Importing upstream Jetty jetty-9.2.1.v20140609
[gigi.git] / lib / jetty / org / eclipse / jetty / util / log / StacklessLogging.java
1 //
2 //  ========================================================================
3 //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 //  ------------------------------------------------------------------------
5 //  All rights reserved. This program and the accompanying materials
6 //  are made available under the terms of the Eclipse Public License v1.0
7 //  and Apache License v2.0 which accompanies this distribution.
8 //
9 //      The Eclipse Public License is available at
10 //      http://www.eclipse.org/legal/epl-v10.html
11 //
12 //      The Apache License v2.0 is available at
13 //      http://www.opensource.org/licenses/apache2.0.php
14 //
15 //  You may elect to redistribute this code under either of these licenses.
16 //  ========================================================================
17 //
18
19 package org.eclipse.jetty.util.log;
20
21 /**
22  * A try-with-resources compatible layer for {@link StdErrLog#setHideStacks(boolean) hiding stacktraces} within the scope of the <code>try</code> block when
23  * logging with {@link StdErrLog} implementation.
24  * <p>
25  * Use of other logging implementation cause no effect when using this class
26  * <p>
27  * Example:
28  * 
29  * <pre>
30  * try (StacklessLogging scope = new StacklessLogging(EventDriver.class,Noisy.class))
31  * {
32  *     doActionThatCausesStackTraces();
33  * }
34  * </pre>
35  */
36 public class StacklessLogging implements AutoCloseable
37 {
38     private final Class<?> clazzes[];
39
40     public StacklessLogging(Class<?>... classesToSquelch)
41     {
42         this.clazzes = classesToSquelch;
43         hideStacks(true);
44     }
45
46     @Override
47     public void close() throws Exception
48     {
49         hideStacks(false);
50     }
51
52     private void hideStacks(boolean hide)
53     {
54         for (Class<?> clazz : clazzes)
55         {
56             Logger log = Log.getLogger(clazz);
57             if (log == null)
58             {
59                 // not interested in classes without loggers
60                 continue;
61             }
62             if (log instanceof StdErrLog)
63             {
64                 // only operate on loggers that are of type StdErrLog
65                 ((StdErrLog)log).setHideStacks(hide);
66             }
67         }
68     }
69 }