1. 程式人生 > >Spring Boot+AOP記錄日誌

Spring Boot+AOP記錄日誌

1、pom.xml中加入web依賴

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、編寫測試Controller和Service
@RestController
public class TestController {
    @Autowired
    private TestService testService;

    @RequestMapping("/hello")
    public String doSomething(String name){
        return testService.hello(name);
    }
}
@Service
public class TestService {
    public String hello(String name){
        try{
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "Hello "+name;
    }
}

3、pom.xml中加入aop依賴

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

4、編寫切面
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(* com.wz.controller..*.*(..))")
    public void logPointcut(){}

    @Before("logPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        log.info("[CLASS_METHOD] : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("[ARGS] : " + Arrays.toString(joinPoint.getArgs()));
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(returning = "ret", pointcut = "logPointcut()")
    public void doAfterReturning(Object ret) {
        log.info("[RESPONSE] : " + ret);
        log.info("[COST TIME] : " + (System.currentTimeMillis() - startTime.get()));
    }

    @AfterThrowing(throwing="ex", pointcut="logPointcut()")
    public void doAfterThrowing(Throwable ex) {
        log.error("[EXCEPTION] : " + ex);
    }

}