spring aop打印接口调用日志

import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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 java.util.StringJoiner;

@Aspect
@Slf4j
@Component
public class PrintLogAop {

    //切点
    @Pointcut("execution(public * com.xxx.controller..*.*(..))")
    public void pointcut() {

    }

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Exception {
        StringBuilder logStr = new StringBuilder();
        //请求url数据
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        logStr.append("请求者ip:").append(getIpAddress(request)).append(",");
        logStr.append("请求地址:").append(request.getRequestURL()).append(",");

        Signature signature = joinPoint.getSignature();
        //获取类信息
        Class clazz = signature.getDeclaringType();
        logStr.append("类:").append(clazz.getName()).append(",");
        logStr.append("方法:").append(signature.getName()).append(",");
        //获取参数
        Object[] args = joinPoint.getArgs();
        StringJoiner param = new StringJoiner("|");
        for (Object obj : args) {
            param.add(formatObject(obj));
        }
        logStr.append("参数:").append(param).append(",");
        Long start = System.currentTimeMillis();
        try {

            //执行方法
            Object obj = joinPoint.proceed();
            logStr.append("返回结果:").append(formatObject(obj)).append(",");
            return obj;
        } catch (Throwable throwable) {
            //处理自定义异常
            //if (throwable instanceof BusinessException) {
            //    throw (BusinessException) throwable;
            //} else {
                throw (Exception) throwable;
            //}
        } finally {
            //打印日志
            Long end = System.currentTimeMillis();
            log.info(logStr + "时间:" + (end - start) + "ms");
        }
    }

    /**
     * 格式化obj
     * @param obj
     * @return
     */
    private String formatObject(Object obj) {
        if(null == obj){
            return null;
        }
        if (obj instanceof String || obj instanceof Long || obj instanceof Integer || obj instanceof Boolean) {
            return (String) obj;
        } else {
            return JSONUtil.toJsonStr(obj);
        }
    }

    /**
     * 获取ip
     * @param request
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

}

Spring Boot 中使用 **AOP(面向切面编程)** 可以非常方便地记录接口调用日志,比如记录请求的 URL、方法名、参数、响应、耗时、IP 地址等信息。这种方式可以统一日志记录逻辑,避免重复代码。 --- ### ✅ 实现步骤 #### 1. 添加依赖(如未引入 AOP) ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` #### 2. 创建切面类(Aspect) ```java import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; 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 public class RequestLogAspect { private static final Logger logger = LoggerFactory.getLogger(RequestLogAspect.class); // 定义切点(controller包下的所有方法) @Pointcut("execution(* com.example.demo.controller..*.*(..))") public void requestLog() {} @Around("requestLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { // 获取请求上下文 RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); if (attributes == null) { return joinPoint.proceed(); } ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes; HttpServletRequest request = requestAttributes.getRequest(); long startTime = System.currentTimeMillis(); try { // 执行原方法 Object result = joinPoint.proceed(); // 记录日志 logger.info("\nURL: {} \nHTTP Method: {} \nClass Method: {}.{} \nArgs: {} \nResponse: {} \nSpend Time: {} ms", request.getRequestURL(), request.getMethod(), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()), result, System.currentTimeMillis() - startTime); return result; } catch (Exception e) { logger.error("接口调用发生异常", e); throw e; } } } ``` --- ### ✅ 输出示例: ``` URL: http://localhost:8080/hello HTTP Method: GET Class Method: com.example.demo.controller.HelloController.hello Args: [] Response: Hello, Spring Boot! Spend Time: 15 ms ``` --- ### ✅ 可选增强功能: - **记录用户信息**:从 `SecurityContext` 或 `token` 中提取用户信息。 - **记录 IP 地址**:通过 `request.getRemoteAddr()` 或代理头获取真实 IP。 - **日志入库**:将日志写入数据库或发送到消息队列(如 Kafka、RabbitMQ)。 - **异常处理**:记录异常堆栈信息,用于排查问题。 --- ### ✅ 示例:记录用户信息(结合 Spring Security) ```java Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { String username = authentication.getName(); logger.info("User: {}", username); } ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值