当业务比较复杂的时候,会希望按照业务来归类log文件,而不是放到一个文件里。
比如说,我希望按照cotroller单位去划分log文件,并且设定每个log文件的size是10MB,那么可以做一下设置。
<?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml" /> <appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"> <discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator"> <key>funcid</key> <defaultValue>all</defaultValue> </discriminator> <sift> <appender name="debug-${funcid}" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> <file>d:/debug-${funcid}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>d:/debug-${funcid}.log.%i</fileNamePattern> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> </sift> </appender> <logger name="jp.co.abc.controller" level="debug"> <appender-ref ref="SIFT" /> </logger> </configuration>
这样,我们可以在出力log的时候,设定funcid来决定,log出力到哪个file里。
每次设置肯定会比较繁琐,我们可以在HandlerInterceptor里来设定funcid,这样就不用每次出力log时都设定funcid了。
public class LogConfigInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if(handler instanceof HandlerMethod){
HandlerMethod hm = (HandlerMethod)handler;
MDC.put("funcid", hm.getBeanType().getSimpleName());
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
MDC.remove("funcid");
}
}
然后在WebMvcConfigurer把这个HandlerInterceptor注册上就好了
@Component
public class MvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogConfigInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**");
}
}