在一些简单的应用中,logger没有几个,但是在一些比较复杂的应用中,往往有这样的场景需要:
<logger name="com.champbay.aaa.mapper.Aaa" level="DEBUG" additivity="false" />
<logger name="com.champbay.bbb.mapper.Bbb" level="DEBUG" additivity="false" />
<logger name="com.champbay.ccc.mapper.Ccc" level="DEBUG" additivity="false" />
<logger name="com.champbay.ddd.mapper.Ddd" level="DEBUG" additivity="false" />
...
<logger name="com.champbay.zzz.mapper.Zzz" level="DEBUG" additivity="false" />
像上面那么多的logger,能不能用下面的正则来替代呢?
<logger name="com.champbay.*.mapper" level="DEBUG" additivity="false" />
结果是不支持的,那么怎么样在logback中支持这样的需求呢?
首先,看看这篇文章:https://stackoverflow.com/questions/48657071/logback-logger-name-with-wildcard/48664150,它采用了ch.qos.logback.core.filter.EvaluatorFilter和ch.qos.logback.classic.boolex.GEventEvaluator来达成这个目的,很方便,但是这种方法的运行环境需要 groovy 的支持,需要在工程中引入 groovy 包,假如你的工程中本身就用到了 groovy,那自然可以,否则就需要引入 groovy 包,姑且不论操作上是否复杂麻烦,就性能来说也是有点点影响的。
直接参考logback的官方文档:http://logback.qos.ch/manual/filters.html,里面提到了第一种方式方法:继承 ch.qos.logback.core.filter.Filter 这个,我个人觉得这个是最好的解决方案。
看一下实现源文件:
package com.champbay.core.log;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
public class MyLogbackFilter extends Filter<ILoggingEvent> {
private Pattern pattern;
private String logPattern;
public String getLogPattern() {
return logPattern;
}
public void setLogPattern(String logPattern) {
this.logPattern = logPattern;
pattern = Pattern.compile(logPattern);
}
@Override
public FilterReply decide(ILoggingEvent event) {
if(pattern == null)
return FilterReply.DENY;
String loggerName = event.getLoggerName();
if(StringUtils.isBlank(loggerName)) {
return FilterReply.DENY;
}
Matcher matcher = pattern.matcher(loggerName);
if(matcher.matches()) {
Level level = event.getLevel();
if(level.isGreaterOrEqual(Level.DEBUG)) {
return FilterReply.ACCEPT;
} else {
return FilterReply.DENY;
}
} else {
return FilterReply.DENY;
}
}
}
<appender name="myAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="com.champbay.core.log.MyLogbackFilter">
<logPattern>com.champbay\..*\.mapper\..*</logPattern>
</filter>
<file>aaa.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>aaa-%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>xxxxxxxxxxxxxxxxxx</pattern>
</encoder>
</appender>
<logger name="com.champbay" level="DEBUG" additivity="false">
<appender-ref ref="myAppender" />
</logger>