Java Tutorial/Log/Log Filter
Версия от 17:44, 31 мая 2010; (обсуждение)
Custom filter
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);
}
}
Setting a Filter on a Logger Handler
import java.util.logging.ConsoleHandler;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Main {
public static void main(String[] argv) throws Exception {
ConsoleHandler handler = new ConsoleHandler();
handler.setFilter(new Filter() {
public boolean isLoggable(LogRecord record) {
return true;
}
});
// Add the handler to a logger
Logger logger = Logger.getLogger("com.mycompany");
logger.addHandler(handler);
}
}
Simple filter
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class MainClass {
private static Logger logger = Logger.getLogger("SimpleFilter");
static class A {
};
static class B {
};
static void sendLogMessages() {
logger.log(Level.WARNING, "message 1!", new A());
logger.log(Level.WARNING, "message 2!", new B());
}
public static void main(String[] args) {
sendLogMessages();
logger.setFilter(new Filter() {
public boolean isLoggable(LogRecord record) {
Object[] params = record.getParameters();
if (params == null)
return true;
if (record.getParameters()[0] instanceof A)
return true;
return false;
}
});
logger.info("After setting filter..");
sendLogMessages();
}
}