View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.util.log;
5   
6   import java.util.logging.Handler;
7   import java.util.logging.Level;
8   import java.util.logging.Logger;
9   
10  /**
11   *	@author Romain PELISSE, belaran@gmail.com
12   *  @author Roberto Ferranti - rferranti@users.sourceforge.net
13   *  Thanks to Jesse Glick for the bug report.
14   *
15   */
16  public class ScopedLogHandlersManager {
17  
18  	private static final String PACKAGE_NAME = "net.sourceforge.pmd";
19  
20      @SuppressWarnings("PMD.LoggerIsNotStaticFinal")
21      private Logger logger;
22      private Level oldLogLevel;
23      private Handler[] oldHandlers;
24      private Handler[] newHandlers;
25  
26      public ScopedLogHandlersManager(Level level, Handler... handlers) {
27          newHandlers = handlers;
28          logger = Logger.getLogger(PACKAGE_NAME);
29          oldHandlers = logger.getHandlers();
30          oldLogLevel = logger.getLevel();
31          logger.setLevel(level);
32          //The Ant logger filters itself
33          for (Handler handler : oldHandlers) {
34              logger.removeHandler(handler);
35          }
36          for (Handler handler : newHandlers) {
37              logger.addHandler(handler);
38          }
39      }
40  
41      public void close() {
42          for (Handler handler : newHandlers) {
43              logger.removeHandler(handler);
44          }
45          for (Handler handler : oldHandlers) {
46              logger.addHandler(handler);
47          }
48          logger.setLevel(oldLogLevel);
49      }
50  }