LogAspect.java 2.56 KB
package vion.advice;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HlQ
 * @date 2024/1/17
 */
@Component
@RequiredArgsConstructor
@Aspect
@Slf4j
public class LogAspect {

    private final ObjectMapper objectMapper;

    @Pointcut("execution(* vion.controller.*.*(..))")
    public void logPointcut() {
    }

    @Before("logPointcut()")
    public void doBefore(JoinPoint joinPoint) throws JsonProcessingException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjUtil.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);

        String requestId = (String) request.getAttribute("requestId");
        MDC.put("requestId", requestId);
        log.info("Request URL:{}, Method:{}, IP:{}, Arguments:{}",
                request.getRequestURI(),
                request.getMethod(),
                ServletUtil.getClientIP(request),
                objectMapper.writeValueAsString(request.getParameterMap())
        );
    }

    @AfterReturning(pointcut = "logPointcut()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) throws JsonProcessingException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjUtil.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        long startTime = (Long) request.getAttribute("startTime");
        long responseTime = System.currentTimeMillis() - startTime;

        String resStr = objectMapper.writeValueAsString(result);
        if (resStr.length() > 1000) {
            resStr = resStr.substring(0, 1000);
        }
        log.info("Response time: {} ms. Return value: {}",
                responseTime,
                resStr);
        MDC.remove("requestId");
    }

}