Java logging Filter Interface


Recently, I switched from using log4j to java logging, and I needed a way to selectively constrain logging to a specific set of classes, or methods.  So I came up with the following example. Since there are a few examples on the java logging Filter interface, I am sharing this example.

Hopefully it's useful to others.
         
SelectiveLogFilter filter = new SelectiveLogFilter();
filter.add(MyApp.class.getName());
consoleHandler.setFilter(filter);


/\*\*
 \* A simple logging filter to allow multi per class logging
 \*
 \*/
public class SelectiveLogFilter implements Filter {
    private HashSet classLogSet = new HashSet();
    private HashSet methodLogSet = new HashSet();

    /\*\*
     \* Adds a name to the set of loggable classes
     \*
     \* @param  className  canonical class name e.g. App.class.getName()
     \*/
    public void add(String className) {
        classLogSet.add(className);
    }

    /\*\*
     \* Removes a name from the set loggable classes
     \*
     \* @param  className  canonical class name e.g. App.class.getName()
     \*/
    public void remove(String className) {
        classLogSet.remove(className);
    }

    /\*\*
     \* Adds a method name to the set of loggable classes
     \*
     \* @param  methodName  canonical method name e.g.
     \* App.class.getName()+"methodName"
     \*/
    public void addMethod(String methodName) {
        methodLogSet.add(methodName);
    }

    /\*\*
     \* Removes a name from the set loggable classes
     \*
     \* @param  methodName  canonical method name e.g.
     \* App.class.getName()+"methodName"
     \*/
    public void removeMethod(String methodName) {
        methodLogSet.remove(methodName);
    }

    /\*\*
     \* Clears the loggable Class Set (effectively turns off logging)
     \*/
    public void reset() {
        classLogSet.clear();
    }

    /\*\*
     \* Clears the loggable Method Set
     \*/
    public void resetMethodSet() {
        methodLogSet.clear();
    }

    /\*\*
     \* {@inheritDoc}
     \*/
    public boolean isLoggable(LogRecord record) {
        return classLogSet.contains(record.getSourceClassName()) || 
                                      methodLogSet.contains(record.getSourceMethodName());
    }
}

Comments:

Post a Comment:
Comments are closed for this entry.
About

hamada

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today