根据业务归类log文件

阅读更多

当业务比较复杂的时候,会希望按照业务来归类log文件,而不是放到一个文件里。

比如说,我希望按照cotroller单位去划分log文件,并且设定每个log文件的size是10MB,那么可以做一下设置。


	
    
        
            funcid
            all
        
        
            
            	
					${FILE_LOG_PATTERN}
				
                d:/debug-${funcid}.log
				
					d:/debug-${funcid}.log.%i
				
				
					10MB
				
            
        
    
    
    	
    

 这样,我们可以在出力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/**");
	}
}

 

你可能感兴趣的:(logback,log,spring,spring,boot)