使用AOP 自动打印方法进出, 耗时 logger
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注解:
/** * ************************************************************************* * <PRE> * @ClassName: : Mylog * * @Description: : 自定义注解, 实现对方法的进 出 ,运行时间 打印logger, * * @Creation Date : 8 Aug 2019 3:02:36 PM * * @Author : Sea * * * </PRE> ************************************************************************** */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Mylog { String value() default ""; }
切片:
@Aspect @Component public class MylogAspect { private static Logger logger = LoggerFactory.getLogger(MylogAspect.class); @Around("@annotation(Mylog)") // 作用到注释@Mylog标记的方法上 public Object handleSeaAnnotionAOPMethod(ProceedingJoinPoint joinPoint, Mylog Mylog) throws Throwable { long start = System.currentTimeMillis(); // 获取方法的 全类名 com.sea.controller.XXXcontroller.getdate() MethodSignature signature = (MethodSignature) joinPoint.getSignature(); String className = signature.getDeclaringType().getSimpleName(); // 获取注解作用方法名 eg:getdata String methodName = joinPoint.getSignature().getName(); // 获取方法-- // Method method = joinPoint.getTarget().getClass().getMethod(methodName, signature.getParameterTypes()); // Method method = getMethod(joinPoint); logger.info("&&&&&& enter into the class {} -> method {} &&&&&&", className, methodName); // ################################################################ Object object = joinPoint.proceed(); System.err.println(className); long end = System.currentTimeMillis(); logger.info("&&&&&& end the class {} -> method {} &&&&&&", className, methodName); logger.info(" ^^^^^^^^^run the method {} total cost time : {} ms ^^^^^^^^",methodName, (end - start)); return object; }}
Test:
@GetMapping("/get") @Mylog public String getData() { return "nihao"+ UUID.randomUUID(); }
结果: .....