Setting Filter at Logger level

In the post “Setting Filter at Handler level”, I showed how to set filter at handler level. In this post I will explain how to set filter at logger level.

An use case of setting filter at logger level, is restricting logging of messages based on the user who logged it.

Custom Filter


1  package logging;
2  
3  import java.util.logging.Filter;
4  import java.util.logging.LogRecord;
5  
6  public class CustomFilter2 implements Filter {
7   private String userName;
8   
9   @Override
10  public boolean isLoggable(LogRecord logRecord) {
11      if(logRecord.getMessage().contains(userName))
12          return true;
13      else
14          return false;
15  }
16 
17  public String getUserName() {
18      return userName;
19  }
20 
21  public void setUserName(String userName) {
22      this.userName = userName;
23  }
24 }

In the method isLoggable, if the logRecord’s message contains userName matching CustomFilter2’s userName, the message is logged otherwise it is ignored.

Main Class


1  package logging;
2  
3  import java.util.logging.Logger;
4  
5  public class LoggingDemo6 {
6   public static void main(String[] args) {
7       Logger logger = Logger.getLogger("logger");
8       
9       CustomFilter2 customFilter = new CustomFilter2();
10      logger.setFilter(customFilter);
11      
12      customFilter.setUserName("user1");
13      logger.info("user1: Hello my name is user1");
14      logger.info("user2: Hello my name is user2");
15          
16      customFilter.setUserName("user2");
17      logger.info("user1: Welcome to user1 world");
18      logger.info("user2: Welcome to user2 world");
19  }
20 }

At line 9, we create an instance of CustomFilter2 and set the filter at logger level at line 10.

At line 12, we set the userName to “user1”. So in case of line 13 and 14 only the log messages containing “user1” is allowed.

At line 16, we set the userName to “user2”. So in case of line 17 and 18 only the log messages containing “user2” is allowed.

Output

Oct 08, 2017 12:18:05 PM logging.LoggingDemo6 main
INFO: user1: Hello my name is user1
Oct 08, 2017 12:18:06 PM logging.LoggingDemo6 main
INFO: user2: Welcome to user2 world

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s