AOP实现接口日志打印

package com.yuvision.pircvbs.config;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
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;

@Aspect
@Component
@Slf4j
public class WebLogAspect {

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

    @Pointcut("execution(public * com.yuvision.pircvbs.*.controller.*.*(..))")
    private void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            startTime.set(System.currentTimeMillis());
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Object params[] = joinPoint.getArgs();
            log.info("-------------------------------------- 请求开始  -----------------------------------------------------");
            log.info(">>> 方法地址: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info(">>> 请求入参: {}", Arrays.toString(params));
            log.info(">>> 请求地址: " + request.getRequestURL().toString());
            log.info(">>> 请求ip: " + request.getRemoteAddr());
        } catch (Exception e) {
             log.info("日志打印异常 -> {}",e.getMessage());
        }
    }

    @After("logPointCut()")
    public void daAfter() {
        log.info("-------------------------------------- 请求结束  -----------------------------------------------------");
    }

    @AfterReturning(returning = "result", pointcut = "logPointCut()")
    public void daAfterReturn(JoinPoint joinPoint, Object result) {
        try {
            log.info(">>> 响应时间: {}", (System.currentTimeMillis() - startTime.get()) + " ms");
            log.info(">>> 返回内容: {}", new JSONObject(result));
        } catch (Exception e) {
            log.info(">>> 返回内容: {}", result);
        }
    }
}
posted @ 2025-08-28 11:20  星空与沧海  阅读(5)  评论(0)    收藏  举报