一、自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParamLog {
String description() default "";
}
二、自定义切面
这里用的@Around环绕通知
@Aspect
@Component
@Slf4j
public class LogAspect {
@Around(value = "@annotation(***package name***.ParamLog)")
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
//获取所有参数值的数组
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
//获取方法名
String methodName = method.getName();
//获取类名
String className = method.getDeclaringClass().getName();
log.info("类名: {},方法名: {},入参: {}", className, methodName, args);
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
log.info("类名: {}, 方法名: {}, 出参: {}, 耗时: {} ms",
className, methodName, JSON.toJSONString(result), endTime - startTime);
return result;
}
}
三、方法上添加注解
在需要打印入参、出参日志的方法上添加@ParamLog注解
注:如果该方法接口调用量很大,请谨慎使用,否则会造成大量的日志文件,占用内存