java 自定义切面日志

1、maven 依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
	
    <dependency>
       <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.43</version>
    </dependency>

2、自定义注解:

/**
 * 自定义日志注解
 */
@Retention(RetentionPolicy.RUNTIME)     //什么时候使用该注解,我们定义为运行时;
@Target({ElementType.METHOD})           //注解用于什么地方,我们定义为作用于方法上
@Documented
public @interface WebLog {              //注解名为 WebLog;


    /**
     * 日志描述
     *
     */

    String describetion() default "";   //定义一个属性,默认为空字符串;
}

3 、写切面类

package com.it.demo.aspect;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
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;


@Slf4j
@Aspect
@Component
public class WebLogAspect {

    // 换行符
    private static final String LINE_SEPARATOR = System.lineSeparator();

    /*
    以自定义 @webLog 注解作为切点
     */
    @Pointcut("@annotation(com.it.demo.aspect.WebLog)")  //方自定义@webLog 注解全限路径
    public void webLog(){
        
    }
    
    
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        long startTime = System.currentTimeMillis();
        //执行切点,执行切点后,会去依次调用 @Before -> 接口逻辑代码 -> @After -> @AfterReturning;
        Object result = proceedingJoinPoint.proceed();
        log.info("响应数据 : {}", JSONObject.toJSONString(result));
        log.info("接口访问耗时 : {}",System.currentTimeMillis()-startTime);
        return result;
    }

    /**
     * 访问前嵌入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws  Throwable{
        ServletRequestAttributes attributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取接口描述
        String aspectLogDescribetion = getAspectLogDescribetion(joinPoint);
        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印描述信息
        log.info("Description    : {}", aspectLogDescribetion);
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        log.info("Request Args   : {}", JSONObject.toJSONString(joinPoint.getArgs()));
        
    }

    @After("webLog()")
    public void doAfter(JoinPoint joinPoint) throws  Throwable{
        log.info("===================================== end ====================================" + LINE_SEPARATOR);
    }


    /**
     * 获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     */
    public String getAspectLogDescribetion(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(WebLog.class).describetion());
                    break;
                }
            }
        }
        return description.toString();
    }

}

4、使用:

在这里插入图片描述

5、看效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值