springboot使用切面捕获异常并且使用注解收集日志

发布时间 2023-10-29 22:00:33作者: MarcoXiang

项目目录

 MySysLog

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface MySysLog {
    String value() default "";
}

SysLogAop

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.annotation.MySysLog;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SysLogAop {
    @Around("@annotation(mySysLog)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, MySysLog mySysLog) throws Throwable {
        long startTime = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        MySysLog annotation = signature.getMethod().getAnnotation(MySysLog.class);
        String name = proceedingJoinPoint.getTarget().getClass().getName();
        String signatureName = signature.getName();
        Object[] args = proceedingJoinPoint.getArgs();
        try {
            Object proceed = proceedingJoinPoint.proceed(); // 执行方法
            // 记录方法执行后的日志
            long endTime = System.currentTimeMillis();
            System.out.println("@annotation(mySysLog) method executed. Time taken: " + (endTime - startTime) + "ms");
            return proceed;
        } catch (Exception e) {
            System.out.println("error");
            return null;
        }

    }

}

DemoController

import org.example.service.impl.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @Autowired
    DemoService demoService;

    @RequestMapping("/test")
    public String test(){

        System.out.println(1);
        return demoService.testRequest();
    }
}

DemoService

import org.springframework.stereotype.Service;

@Service
public interface DemoService {
    String testRequest();
}

DemoServiceImpl

import org.example.annotation.MySysLog;
import org.example.service.impl.DemoService;
import org.springframework.stereotype.Service;

@Service
public class DemoServiceImpl implements DemoService {
    @MySysLog(value = "自定义参数")
    @Override
    public String testRequest() {
        if (true){
            System.out.println(1/0);
        }
        return "test";
    }
}

ApplicationStartup

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 */
@SpringBootApplication
//@EnableAspectJAutoProxy
public class ApplicationStartup {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationStartup.class, args);
    }
}