spring boot aop 方法请求参数日志打印

1.引入starter


            org.springframework.boot
            spring-boot-starter-aop

2.切面代码

package com.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
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 com.alibaba.fastjson.JSON;

@Aspect
@Component
public class RequestAspect {

    private Logger logger = Logger.getLogger(RequestAspect.class);
    
    @Pointcut("execution(public * com.web.controller.*.*(..))")
    public void log(){}
    
    @Before("log()")
    public void exBefore(JoinPoint joinPoint){
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        logger.info("url:"+request.getRequestURL());
        logger.info("method:"+request.getMethod());
        logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        logger.info("args:"+JSON.toJSONString(joinPoint.getArgs()));
    }
    
    @After("log()")
    public void exAfter(JoinPoint joinPoint){
        logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()
                +"方法执行完毕!");
    }
    
    @AfterReturning(returning="result",pointcut="log()")
    public void exAfterReturning(Object result){
        logger.info("执行返回值:"+JSON.toJSONString(result));
    }
}
 

你可能感兴趣的:(spring boot aop 方法请求参数日志打印)