log4j2(二) 自定义filter-ThreadFilter根据线程名过滤日志

x33g5p2x  于2021-12-25 转载在 其他  
字(3.2k)|赞(0)|评价(0)|浏览(601)

背景

项目最新接入了一个sdk,但是这个SDK打印了很多无关紧要的DEBUG日志,造成了严重的信息干扰,现在想去掉这个SDK中指定线程的DEBUG日志

解决方案

使用Log4j2的插件扩展功能自定义一个插件-ThreadFilter, 参考链接中的Filter部分

代码示例

相关的解释都已经放在了代码和配置中, 注意查看注释

Java代码

package com.test.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;

/** * filter log by thread name and log level * * @author Keven * @version 1.0 * date: 2020-02-26 */
 //声明插件的类型,名字等信息
@Plugin(name = "ThreadFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
public class ThreadFilter extends AbstractFilter {

    private String threadName;
    private Result onMatch;
    private Result onMisMatch;
    private Level level;

    public ThreadFilter(String threadName, Result onMatch, Result onMisMatch, Level level) {
        super();
        this.threadName = threadName;
        this.onMatch = onMatch;
        this.onMisMatch = onMisMatch;
        this.level = level;
    }

    /** * Create a ThreadFilter instance. * * @param threadName The thread name * @param match The action to take on a match. * @param mismatch The action to take on a mismatch. * @param level log level * @return The created MyCustomFilter. */
    //@PluginFactory注解对应的必须使用一个静态的方法,传入的参数用@PluginAttribute修饰
    @PluginFactory
    public static ThreadFilter createFilter(@PluginAttribute("threadName") final String threadName,
                                            @PluginAttribute("onMatch") final Result match,
                                           @PluginAttribute("onMismatch") final Result mismatch,                                        @PluginAttribute("level") final Level level) {
        assert StringUtils.isNotBlank(threadName);
        final Result onMatch = match == null ? Result.NEUTRAL : match;
        final Result onMismatch = mismatch == null ? Result.DENY : mismatch;
        return new ThreadFilter(threadName, onMatch, onMismatch, level);
    }

    @Override
    public Result filter(LogEvent event) {
    	//你的业务逻辑,这里是根据线程前缀名,以及日志等级来过滤
        if (event.getLevel().name().equals(this.level.name()) && event.getThreadName().startsWith(threadName)) {
            return this.onMatch;
        }
        return this.onMisMatch;
    }

    @Override
    public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
        return super.filter(logger, level, marker, msg, t);
    }
}

使用

<?xml version="1.0" encoding="UTF-8"?>
<!--注意这里packages填写的是filter所对应的包名,必不可少-->
<Configuration status="warn" name="MyApp" packages="com.test.filter">
  <Appenders>
    <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/app-%d{MM-dd-yyyy}.log.gz">
      <!--此处的参数名称于@PluginFactory所对应的方法中的参数名称对应-->
      <ThreadFilter threadName="XXX-Thread" onMatch="DENY" onMismatch="ACCEPT" level="DEBUG"/>
      <PatternLayout>
        <pattern>%d %p %c{1.} [%t] %m%n</pattern>
      </PatternLayout>
      <TimeBasedTriggeringPolicy />
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>
</Configuration>

相关文章