1. 过滤器实现步骤
1. 规则类实现Filter接口,重写isLoggable(LogRecord record)方法;
2. 创建自定义规则(注意:本文采用的规则实在静态代码块中加载的,要注意result变量的状态);
3. 业务代码中的日志记录器配置过滤器(注意:同一时刻只能由一个过滤器);
logger.setFilter(logFilterRule);
2. 过滤器实现范例
2.1. 创建过滤器规则类(LogFilterRule)
public class LogFilterRule implements Filter {
private static final String LOGGER_NAME = "com.study.section5.sentence6";
private static final String[] METHODS = {"method1", "method2"};
private boolean result = false;
@Override
public boolean isLoggable(LogRecord record) {
if (record == null) {
throw new NullPointerException("record is null;");
}
if (!LOGGER_NAME.equals(record.getLoggerName())){
result = false;
return false;
}
for (String methodName : METHODS){
if (record.getSourceMethodName().equals(methodName) ){
result = true;
break;
}
}
if (!result){
return false;
}
if ( record.getLevel().intValue() > 3){
result = false;
return TRUE;
}else {
return FALSE;
}
}
}
2.2. 创建业务类,即产生日志的类(LogCreate)
class LogCreate {
private static final Logger loggerRoot = Logger.getLogger("");
private static final Logger loggerPackage = Logger.getLogger("com.study.section5");
private static final Logger loggerClass = Logger.getLogger("com.study.section5.sentence6");
static {
LogFilterRule logFilterRule = new LogFilterRule();
loggerRoot.setFilter(logFilterRule);
loggerPackage.setFilter(logFilterRule);
loggerClass.setFilter(logFilterRule);
}
public void method1(){
loggerClass.finer("method1 finer log");
loggerClass.info("method1 info log");
loggerClass.severe("method1 sever log");
}
public void method2(){
loggerClass.finer("method2 finer log");
loggerClass.info("method2 info log");
loggerClass.severe("method2 sever log");
}
public void method3(){
loggerClass.finer("method3 finer log");
loggerClass.info("method3 info log");
loggerClass.severe("method3 sever log");
}
}
2.3. 创建测试类(Test)
class Test{
private static final LogFilterRule LOG_FILTER_RULE = new LogFilterRule();
public static void main(String[] args) {
LogCreate logCreate = new LogCreate();
logCreate.method1();
logCreate.method2();
logCreate.method3();
}
}
3. 实验结果
1. 方法名只有method1和method2的日志能正常生成;
2. 只有日志级别高于3级别的能正常生成;(SEVER,WARNING,INFO)
![image.png](https://i-blog.csdnimg.cn/blog_migrate/88eeebe217d2065eac07a30e7b018391.png)
wolai广告:
给大家推荐一个国产的类Notion笔记软件,挺好用的本文也有wolai版,希望大家可以用用;免费的呦!!!也可以使用我的邀请码,双方都可以得积分兑换会员;
文章链接:https://www.wolai.com/a6f22oDvi1xALxAc2tZfWS
邀请码信息:
邀请码:V4SIZAI
HardStone磐石诚挚邀请您注册并体验 wolai:
https://www.wolai.com/signup?invitation=V4SIZAI