springboot中统一日志输出logback

2021-06-11 19:03

阅读:604

标签:try   property   tty   过滤   也会   url   for   empty   map   

1.背景

为了便于分析和记录系统的运行,一个系统输出其运行的关键日志是非常必要的

比如输出:请求参数、请求url、请求方式、执行的sql、重要操作的日志、响应结果等

而这些日志中,大部分不需要我们手动对每个接口去输出,主需要统一配置就可以了

2.实际生产运用步骤

步骤一:在resources下添加logback文件,这个问价基本上每个项目都是一样的,拷贝过来就可以使用

技术图片技术图片
xml version="1.0" encoding="UTF-8"?>

configuration scan="false" scanPeriod="60 seconds" debug="false">
    
    property name="LOG_HOME" value="logs"/>
    property name="appName" value="log">property>
    property name="logLevel" value="info">property>
    
    
    appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        
        encoder>
            pattern>%d{MM-dd HH:mm:ss.SSS} [%thread] %level %logger{50} - %msg%npattern>
            charset>UTF-8charset>
        encoder>
    appender>

    
    appender name="all" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        append>trueappend>
        
        filter class="ch.qos.logback.classic.filter.LevelFilter">
            level>debuglevel>
        filter>
        
        file>${LOG_HOME}/${appName}-all.logfile>
        
        rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            fileNamePattern>${LOG_HOME}/%d{yyyy-MM-dd}/${appName}-all.%d.%i.log.zipfileNamePattern>
            
            MaxHistory>30MaxHistory>
            
            timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                maxFileSize>10KBmaxFileSize>
                
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        
        encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            pattern>%d{MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%npattern>
            charset>UTF-8charset>
        encoder>
    appender>

    
    appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        append>trueappend>
        filter class="ch.qos.logback.classic.filter.LevelFilter">
            level>errorlevel>
        filter>
        file>${LOG_HOME}/${appName}-error.logfile>
        rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            fileNamePattern>${LOG_HOME}/%d{yyyy-MM-dd}/${appName}-error.%d.%i.log.zipfileNamePattern>
            MaxHistory>30MaxHistory>
            timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                maxFileSize>10MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            pattern>%d{MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%npattern>
            charset>UTF-8charset>
        encoder>
    appender>

    
    root level="${logLevel}">
        appender-ref ref="stdout"/>
        appender-ref ref="all"/>
        appender-ref ref="error"/>
    root>
configuration>
View Code

步骤二:添加一个过滤器,在过滤器中统一输出日志

技术图片技术图片
package com.ldp.user.common.interceptor;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Copyright (C) XXXXX科技有限公司
 * @Author: LI DONG PING
 * @Date: 2019/4/22 17:47
 * @Description:
 */
@Component
@Slf4j
public class HttpServletRequestWrapperFilter implements Filter {
    private final String CHARSET = "UTF-8";

    @Override
    public void doFilter(ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 自定义线程名称
        Thread.currentThread().setName(RandomUtil.randomString(10));
        MultiReadHttpServletRequest requestWrapper = new MultiReadHttpServletRequest(request);
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response, CHARSET);
        String contentType = requestWrapper.getHeader(HttpHeaders.CONTENT_TYPE);
        String url = requestWrapper.getRequestURL().toString();
        if (url.contains("actuator") || url.contains("swagger") || url.contains("csrf")) {
            chain.doFilter(requestWrapper, responseWrapper);
            byte[] bytes = responseWrapper.getBytes();
            response.getOutputStream().write(bytes);
            return;
        }
        if (!url.contains("actuator")) {
            log.info("ContentType: {}", contentType);
            log.info("请求地址: {}", url);
            log.info("请求方法: {}", requestWrapper.getMethod().toUpperCase());
            if (isTextContentType(contentType)) {
                String params = requestWrapper.getQueryString();
                if (!StrUtil.isEmpty(params)) {
                    log.info("请求参数: {}", params);
                }
                String body = ServletUtil.getBody(requestWrapper);
                if (!StrUtil.isEmpty(body)) {
                    log.info("请求参数[body]: {}", body);
                }
            }
            long start = System.currentTimeMillis();
            chain.doFilter(requestWrapper, responseWrapper);
            long end = System.currentTimeMillis();
            byte[] bytes = responseWrapper.getBytes();
            if (isTextContentType(response.getContentType())) {
                try {
                    log.info("响应结果: {}", new String(bytes, CHARSET));
                } catch (Exception ex) {
                    log.error("响应异常", ex);
                }
            }
            log.info("HTTP状态: {}", responseWrapper.getStatus());
            long diff = end - start;
            if (diff ) {
                log.info("处理时长: {}毫秒", diff);
            } else {
                log.error("处理时长: {}毫秒,url:{}", diff, url);
            }
            response.getOutputStream().write(bytes);
        } else {
            chain.doFilter(requestWrapper, responseWrapper);
            byte[] bytes = responseWrapper.getBytes();
            response.getOutputStream().write(bytes);
        }
    }

    private boolean isTextContentType(String contentType) {
        return contentType != null && (contentType.contains(MediaType.TEXT_PLAIN_VALUE) ||
                contentType.contains(MediaType.TEXT_XML_VALUE) ||
                contentType.contains(MediaType.TEXT_HTML_VALUE) ||
                contentType.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE) ||
                contentType.contains(MediaType.APPLICATION_JSON_VALUE) ||
                contentType.contains(MediaType.APPLICATION_XML_VALUE));
    }
}
View Code

步骤三:引入日志输出对象

 // 方式一:lombok日志输出对象引入,变量名为log (推荐使用)
@Slf4j

 // 方式二:日志输出对象引入 变量名为logger
 private final static Logger logger = LoggerFactory.getLogger(UserOrderController.class);

技术图片

 步骤四:使用

 /**
     * 测试统一日志输出
     *
     * @param message
     * @return
     */
    @GetMapping("/log")
    public BaseResponse log(String message) {
        // 注意这个System.out.println的输出,只会输出到控制台,不能输出到日志文件,
        // 而且效率很低,只用于平时开发,实际生产几乎不可能使用
        System.out.println("message=" + message);
        logger.debug("debug日志输出,message={}", message);
        // 这两种写法一样
        logger.debug("debug日志输出,message=" + message);
        logger.info("info日志输出,message={}", message);
        logger.error("error 日志输出,message={}", message);
        // 模拟输出错误堆栈信息
        try {
            if ("abc".equals(message)) {
                Integer value = Integer.valueOf(message);
                logger.info("value=" + value);
            }
        } catch (Exception e) {
            logger.error("数字转换异常:", e.getMessage());
            logger.error("数字转换异常:", e);
        }
        // 不处理的异常
        Integer value2 = Integer.valueOf(message);
        logger.info("value2=" + value2);
        return ResponseBuilder.success("统一参数检查.....");
    }

步骤五:模拟请求测试

技术图片技术图片
 /**
     * 统一日志输出测试
     */
    @Test
    void logTest() {
        String url = urlLocal + "/userOrder/log";
        System.out.println("请求地址:" + url);
        HttpRequest request = HttpUtil.createRequest(Method.GET, url);
        Map map = new TreeMap();
        // 业务参数
        map.put("message", "1000");

        // 公用参数
        map.put("appid", "1001");
        map.put("sequenceId", "seq" + System.currentTimeMillis());
        map.put("timeStamp", System.currentTimeMillis());
        map.put("sign", signApi(map, "123456"));
        request.form(map);
        System.out.println("请求参数:" + map);
        request.header("Authorization", token);
        request.setConnectionTimeout(60 * 1000);
        String response = request.execute().body();
        System.out.println("请求结果:" + response);
    }
View Code

日志输出结果:

01-02 08:59:51.760 [rptudgh22m] INFO com.ldp.user.controller.UserOrderController - info日志输出,message=1000
01-02 08:59:51.760 [rptudgh22m] ERROR com.ldp.user.controller.UserOrderController - error 日志输出,message=1000
01-02 08:59:51.760 [rptudgh22m] INFO com.ldp.user.controller.UserOrderController - value2=1000
01-02 08:59:51.796 [rptudgh22m] INFO c.l.u.c.i.HttpServletRequestWrapperFilter - 响应结果: {"message":"success","code":100,"data":"统一参数检查....."}
01-02 08:59:51.797 [rptudgh22m] INFO c.l.u.c.i.HttpServletRequestWrapperFilter - HTTP状态: 200
01-02 08:59:51.798 [rptudgh22m] INFO c.l.u.c.i.HttpServletRequestWrapperFilter - 处理时长: 275毫秒

生成的日志文件夹

技术图片

文字描述内容有限,如果还是不明白可以直接问我,或者在看视频讲解与演示

完美!

springboot中统一日志输出logback

标签:try   property   tty   过滤   也会   url   for   empty   map   

原文地址:https://www.cnblogs.com/newAndHui/p/14221092.html


评论


亲,登录后才可以留言!