SpringBoot自定义注解,AOP统一打印请求日志

1、添加所需依赖

<!-- aop 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<!-- 用于日志切面中,以 json 格式打印出入参 -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2、自定义日志注解

import java.lang.annotation.*;

/**
 * Created by 菜园子 on 2019/5/8.
 */
//运行时使用该注解
@Retention(RetentionPolicy.RUNTIME)
//注解用于方法上
@Target({ElementType.METHOD})
//注解是否将包含在 JavaDoc 中
@Documented
//注解名为 WebLog;
public @interface WebLog {
    /**
     * 日志描述信息
     * 定义一个属性,默认为空字符串
     * @return
     */
    String description() default "";
}

3、配置AOP切面

package com.cyz.song.aspect;

import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.lang.reflect.Method;

/**
 * Created by 菜园子 on 2019/5/8.
 */
@Aspect
@Component
//@Profile({"dev","test"})
public class WebLogAspect {

    protected Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    private final static String LINE_SEPARATOR = System.lineSeparator();

    @Pointcut("@annotation(com.cyz.song.aspect.WebLog)")
    public void webLog(){}

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        logger.info("Response Args  : "+ new Gson().toJson(result).toString() );
        logger.info("Time-Consuming : ms " + (System.currentTimeMillis() - startTime));
        return result;
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String methodDesription = getAspectLogDescription(joinPoint);
        // 打印请求相关参数
        logger.info("**************************** Start ****************************");
        // 打印请求url
        logger.info("URL            : " + request.getRequestURL().toString());
        // 打印描述信息
        logger.info("Description    : " + methodDesription);
        // 打印 Http method
        logger.info("Http Method    : " + request.getMethod());
        // 打印调用Controller的全路径以及执行方法
        logger.info("Class Method   : " + joinPoint.getSignature().getDeclaringTypeName()+" "+joinPoint.getSignature().getName());
        // 打印请求的IP
        logger.info("IP             : " + request.getRemoteAddr());
        // 打印请求入参
        logger.info("Request Args   : " + new Gson().toJson(joinPoint.getArgs()).toString());
    }

    @After("webLog()")
    public void doAfter() throws Throwable{
        logger.info("**************************** End ****************************" + LINE_SEPARATOR);
    }

    public String getAspectLogDescription(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        WebLog webLog = method.getAnnotation(WebLog.class);
        return webLog.description();
    }
}

4、测试使用

@RequestMapping(value = "/login", method = RequestMethod.POST)
@WebLog(description = "请求了用户登录接口")
public ResultObj login(User user) {
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值