1 // 2 // ======================================================================== 3 // Copyright (c) 1995-2016 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 import java.util.HashSet; 22 import java.util.Set; 23 24 /** 25 * A try-with-resources compatible layer for {@link StdErrLog#setHideStacks(boolean) hiding stacktraces} within the scope of the <code>try</code> block when 26 * logging with {@link StdErrLog} implementation. 27 * <p> 28 * Use of other logging implementation cause no effect when using this class 29 * <p> 30 * Example: 31 * 32 * <pre> 33 * try (StacklessLogging scope = new StacklessLogging(EventDriver.class,Noisy.class)) 34 * { 35 * doActionThatCausesStackTraces(); 36 * } 37 * </pre> 38 */ 39 public class StacklessLogging implements AutoCloseable 40 { 41 private final Set<StdErrLog> squelched = new HashSet<>(); 42 43 public StacklessLogging(Class<?>... classesToSquelch) 44 { 45 for (Class<?> clazz : classesToSquelch) 46 { 47 Logger log = Log.getLogger(clazz); 48 // only operate on loggers that are of type StdErrLog 49 if (log instanceof StdErrLog) 50 { 51 StdErrLog stdErrLog=((StdErrLog)log); 52 if (!stdErrLog.isHideStacks()) 53 { 54 stdErrLog.setHideStacks(true); 55 squelched.add(stdErrLog); 56 } 57 } 58 } 59 } 60 61 public StacklessLogging(Logger... logs) 62 { 63 for (Logger log : logs) 64 { 65 // only operate on loggers that are of type StdErrLog 66 if (log instanceof StdErrLog) 67 { 68 StdErrLog stdErrLog=((StdErrLog)log); 69 if (!stdErrLog.isHideStacks()) 70 { 71 stdErrLog.setHideStacks(true); 72 squelched.add(stdErrLog); 73 } 74 } 75 } 76 } 77 78 @Override 79 public void close() 80 { 81 for (StdErrLog log : squelched) 82 log.setHideStacks(false); 83 } 84 }