logback 指定打印日志文件

第一步:配置logback.xml

 
    
        
            INFO
            ACCEPT
            DENY
        
        
            ${XXX_HOME}/log/%d{yyyy-MM-dd}/xxx-api.log
        
        
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%level] %logger - %msg%n
        
    
    
        
    

第二步:代码里使用Logger
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/rest/v1/*", filterName = "apiFilter")
public class ApiFilter implements Filter {
    private static final String API_FILTER_LOGGER_NAME = "apiFilterLogger";

    @Value("${api.filter.enable:false}")
    private boolean apiFilerEnable;
    private Logger logger = LoggerFactory.getLogger(API_FILTER_LOGGER_NAME);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (apiFilerEnable) {
            HttpServletRequest httprequest = (HttpServletRequest) request;
            String currentIp = request.getRemoteAddr();
            Enumeration e = httprequest.getHeaderNames();
            logger.info("============================API Request Start==============================");
            String msg = String.format(">>API Request:[%s] [%s]", httprequest.getMethod(), httprequest.getRequestURL());
            logger.info(msg);
            logger.info(">>>>>Remote Addr:" + httprequest.getRemoteAddr());
            logger.info(">>>>>Query String:" + httprequest.getQueryString());
            logger.info("============Header=================");
            while (e.hasMoreElements()) {
                String k = e.nextElement();
                logger.info(">>>>>" + k + " = " + httprequest.getHeader(k));
            }

            Map paramMap = httprequest.getParameterMap();
            logger.info("============Parameter Map=================");
            paramMap.entrySet().forEach(x -> {
                logger.info(">>>>>" + x.getKey() + "=" + Joiner.on(",").join(x.getValue()));
            });

            logger.info("===================================================================");
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}

你可能感兴趣的:(logback 指定打印日志文件)