logback自定义过滤器

时间:2022-12-10 21:44:01

自定义过滤器

logback.xml配置文件

<appender name="ADD" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="com.test.channel.log.EditLogFilter" />
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/channel_add.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>300</maxHistory>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{HH:mm:ss.SSS},%msg%n</Pattern>
        </layout>
    </appender>


<appender name="ADD_INFO" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0</discardingThreshold>
        <queueSize>1024</queueSize>
        <appender-ref ref="ADD" />
    </appender>


<logger name="com.test.channel" level="INFO"> 
        <appender-ref ref="ADD_INFO" />   
  </logger>


java代码:

过虑器

public class EditLogFilter extends Filter<ILoggingEvent>
{

    @Override
    public FilterReply decide(ILoggingEvent event)
    {
        if (event.getMessage() != null && (event.getMessage().startsWith("add") ||event.getMessage().startsWith("update")))
        {
            return FilterReply.ACCEPT;
        }
        return FilterReply.DENY;
        
    }

}

写日志

String message="{name:上神,role:11,id:10101,operation:添加客户,time:2017-03-15 20:30:22}";
          logger.info("add: {} ",  message);


日志文件内容:

  add: {name:上神,role:11,id:10101,operation:添加客户,time:2017-03-15 20:30:22}