Custom filter : Log Filter « Log « Java Tutorial






import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

class Person {
  private String name = null;

  private int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getAge() {
    return age;
  }
}

class AgeFilter implements Filter {
  public boolean isLoggable(LogRecord record) {
    boolean result = false;
    Object[] objs = record.getParameters();
    Person person = (Person) objs[0];
    if (person != null) {
      int age = person.getAge();
      if (age > 30)
        result = true;
      else
        result = false;
    }
    return result;
  }
}

public class Main {
  public static void main(String args[]) {
    Logger logger = Logger.getLogger("your.logging");
    AgeFilter filter = new AgeFilter();
    logger.setFilter(filter);
    Person person = new Person("YourName", 32);
    logger.log(Level.INFO, "Person has age " + person.getAge(), person);
  }
}








35.3.Log Filter
35.3.1.Simple filter
35.3.2.Setting a Filter on a Logger Handler
35.3.3.Custom filter