java灵活的接口日志打印
日常开发接口时候经常需要和别的开发人员对接, 加上一些必要的日志就显得非常重要了, 方便定位到底是接口返回的数据有问题还是别的地方有问题
本文介绍通过aop自定义一个接口日志增强的逻辑, 在需要的地方加上注解即可, 方便快捷
注解类
首先我们需要自定义一个注解类, 类名自己定(本文用的ResponseLog
)
需要打日志的方法前加上@ResponseLog
即可
/**
* 接口回复日志注解
* @author wangq 2020/3/7 18:43
* @param
* @return
*/
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseLog {
boolean value() default true;// 默认打日志
}
关键点介绍
@Target
: 定义该注解生效的地方@Retention
: 保留到哪个阶段
实现方法
写一个方法, 并注明在扫描到注解的哪个阶段执行
大概有如下注解
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5ekuiNHC-1583579028915)(https://raw.githubusercontent.com/TWanGT/pic/master/20200307185004.png)]
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* @Author: WanG
* @Date: 2020/3/5 20:04
* @version: v1.0
* @description: 请求日志
*/
@Slf4j
@Aspect
@Component
public class ResponseLogAspect {
@Around(value = "@annotation(ResponseLog)")
public Object doAfter(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object result = proceedingJoinPoint.proceed();
log.info("接口回复内容: {}", JSON.toJSONString(result));
return result;
}
}
使用
在需要打日志的接口方法前面加上注解即可
@ResponseLog
@RequestMapping("test")
public String test() {
return "hellow";
}
效果演示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hXQXreVC-1583579028918)(https://raw.githubusercontent.com/TWanGT/pic/master/20200307190143.png)]