【HAVENT原创】使用 Spring Boot 的 AOP 全局记录执行时间日志

基本配置使用:

1. 在 pom.xml 中增加基础类库引用

		<!-- HH: 引入 spring-boot-aop 模块 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

 

2. 配置文件 application.yml 中增加参数配置

spring:
  application:
    name: HAVENT-SPRING-BOOT-DEMO
  aop:
    auto: true
    #proxy-target-class: true

 

3. 新增 KafkaLogAspect.java 拦截器类

package com.havent.demo.aop.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;


@Aspect
@Component
public class KafkaLogAspect {


    /**
     * 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码
     * @return
     */
    @Around(value="execution(* com.havent.demo..*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        long beginTime = System.currentTimeMillis();

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String loggerType = className + "." + methodName;

        Object result = null;
        try {
            System.out.println("【前置通知】:the method 【" + loggerType + "】 begins with " + Arrays.asList(joinPoint.getArgs()));
            //执行目标方法
            result = joinPoint.proceed();
            System.out.println("【返回通知】:the method 【" + loggerType + "】 ends with " + result);
        } catch (Throwable e) {
            System.out.println("【异常通知】:the method 【" + loggerType + "】 occurs exception " + e);
        }

        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        System.out.println("【后置通知】:-----------------end.---------------------- time:" + time);
        return result;
    }


}

 

注意代码中 execution(* com.havent.demo..*(..)) 表示监控范围为 com.havent.demo 下面的所有方法

调用 com.havent.demo 下面的方法,捕获日志如下:

925d1e5b8bdeb5e3e90d3ed68058626ad46.jpg

 

 

进阶操作,监控 controller 操作,获取 web 请求信息:

package com.havent.demo.aop.aspect;

import com.havent.demo.logger.service.KafkaService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
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
public class KafkaLogAspect {

    @Autowired
    private KafkaService logger;


    @Pointcut("execution(public * com.havent.demo.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("IP : " + request.getRemoteAddr());
        System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        //logger.trace("");
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("方法的返回值 : " + ret);

        //logger.trace("");
    }

    //后置异常通知
    @AfterThrowing("webLog()")
    public void throwss(JoinPoint jp){
        System.out.println("方法异常时执行.....");

        //logger.trace("");
    }

    //后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
    @After("webLog()")
    public void after(JoinPoint jp){
        System.out.println("方法最后执行.....");
    }

    //环绕通知,环绕增强,相当于MethodInterceptor
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        System.out.println("方法环绕start.....");
        try {
            Object o =  pjp.proceed();
            System.out.println("方法环绕proceed,结果是 :" + o);
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

}

 

执行结果如下:

 

 

转载于:https://my.oschina.net/u/943746/blog/1926820

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值