Spring Boot無侵入打印前端請求日志

不多廢話,直接上效果

2020-10-19 16:34:17.121 [http-nio-80-exec-2] ?[34mINFO ?[0;39m c.mycompany.settings.spring.WebLogAspect : ++++++++REQUEST URL : GET http://domain/my-service/v1/device/settings
2020-10-19 16:34:17.122 [http-nio-80-exec-2] ?[34mINFO ?[0;39m c.mycompany.settings.spring.WebLogAspect : ++++++++IP : 172.20.0.42
2020-10-19 16:34:17.122 [http-nio-80-exec-2] ?[34mINFO ?[0;39m c.mycompany.settings.spring.WebLogAspect : ++++++++CLASS_METHOD : com.mycompany.settings.core.DeviceSettingsController.list([DeviceSettingsCommand(deviceTypeId=ME, planId=1, deviceVersion=1.0.1, xxxVersion=1.8.1)])
2020-10-19 16:34:17.181 [http-nio-80-exec-2] ?[34mINFO ?[0;39m c.mycompany.settings.spring.WebLogAspect : +++++++++RESPONSE : [DeviceSettingsRepresentation(featureCode=cmd_timezone_40, featureName=Set Timezone, featureLabel=Set Timezone, featureDesc=null, uri=null, xxxSupportVersion=null, featureType=null, available=false, reason=This feature is currently in development, and will be available in a future release.), DeviceSettingsRepresentation(featureCode=cmd_camera_framerate_39, featureName=Camera Framerate, featureLabel=Camera Framerate, featureDesc=The xxx system automatically switches the Cam current refresh frequency based on the device's local time zone. It's not always accurate, though, and you can try doing a switch between 50Hz and 60Hz to fix the problem when your device's screen appears spent., uri=null, xxxSupportVersion=null, featureType=null, available=false, reason=This feature is currently in development, and will be available in a future release.), DeviceSettingsRepresentation(featureCode=cmd_virtual_background_38, featureName=Virtual Background, featureLabel=Virtual Background, feature...略
2020-10-19 16:34:17.181 [http-nio-80-exec-2] ?[34mINFO ?[0;39m c.mycompany.settings.spring.WebLogAspect : ++++++++SPEND TIME : 60 ms


步驟很簡單,直接添加一個aspect類即可,直接上代碼

注意:@Pointcut注解,正確填寫controller的路徑,否則不生效

import com.mycompay.myproject.common.constant.AppCons;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 * controller日志切面類
 * Created by author on 2018/12/1.
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.mycompany.settings.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        // 接收到請求,記錄請求內(nèi)容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印請求信息
        log.info("++++++++REQUEST URL : {} {}", request.getMethod(), request.getRequestURL().toString());
        log.info("++++++++IP : {}", request.getRemoteAddr());
        log.info("++++++++CLASS_METHOD : {}.{}({})", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 處理完請求,返回內(nèi)容和響應時間
        String respContent = Optional.ofNullable(ret).map(Object::toString).orElse("");
        log.info("+++++++++RESPONSE : {}{}", StringUtils.substring(respContent,0, AppCons.LENGTH_OF_WEB_LOG),
                respContent.length() > AppCons.LENGTH_OF_WEB_LOG ? "...略" : "");
        log.info("++++++++SPEND TIME : {} ms", (System.currentTimeMillis() - startTime.get()));
        startTime.remove();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。