首页 > 程序开发 > 软件开发 > 其他 >

Spring Boot+AOP记录日志

2017-04-19

Spring Boot+AOP记录日志:1、pom xml中加入web依赖。

Spring Boot+AOP记录日志:1、pom.xml中加入web依赖。

    org.springframework.boot
    spring-boot-starter-web

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依赖

  
    org.springframework.boot
    spring-boot-starter-aop

4、编写切面

@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    ThreadLocal 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);
    }

}

相关文章
最新文章
热点推荐