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

基本配置使用:java

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

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

 

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

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

 

3. 新增 KafkaLogAspect.java 拦截器类app

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 下面的全部方法spring-boot

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

 

 

进阶操做,监控 controller 操做,获取 web 请求信息:3d

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;
        }
    }

}

 

执行结果以下:日志

相关文章
相关标签/搜索