需求背景:每个接口都有入参出参,如果每次都需要自己写代码打印入参出参,大家是否觉得很繁琐,为了减少冗余代码,提高同时工作效率,减少工作量,于是给代码加了aop统一拦截。
其实其他项目里已经有aop拦截,但是需要自己去加注解实现,如果每个接口需要自己手动加一个注解才会打印日志,我依然还是觉得很麻烦,为了大家专注于自己的需求开发,于是进行优化。
首先加注解代码如下:
/**
* log注解
*
* @author keying
*/
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
}
/**
* 日志统一打印
* @author keying
* @date 2022-11-03 19:40:28
*/
@Aspect
@Component
@Slf4j
public class LogAspect2 {
private final String REQUEST = "REQUEST URL:{},REQUEST METHOD:{},REQUEST PARAM:{}";
private final String RESPONSE = "RESPONSE URL:{},RESPONSE METHOD:{},RESPONSE PARAM:{}";
@Pointcut("@annotation(com.ztocc.tms.operates.controller.config.LogAnnotation)")
public void requestAspect() {
}
@Before(value = "requestAspect()")
public void methodBefore(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info(REQUEST, request.getRequestURI(), request.getMethod(),
JSON.toJSONString(Arrays.toString(joinPoint.getArgs())));
}
@AfterReturning(returning = "o", pointcut = "requestAspect()")
public void methodAfter(Object o) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info(RESPONSE, request.getRequestURI(), request.getMethod(),
JSONObject.toJSONString(o));
}
}
@PostMapping("/query_page")
@LogAnnotation
public Result<PageVo<ManageScanPageVO>> queryPage(@RequestBody ManageScanPageReq req) {
}
从图上可以看到
第一步:写一个注解,通过Aspect技术把拦截注解修饰的方法。
第二步:把注解写到需要打印日志的接口上。
于是通过修改上面代码,可以使代码更简洁,并且开发人员不需要关心是否加注解来打印日志。
/**
* 日志统一打印
* @author keying
* @date 2022-11-03 19:40:28
*/
@Aspect
@Component
@Slf4j
public class LogAspect {
private final String REQUEST = "REQUEST URL:{},REQUEST METHOD:{},REQUEST PARAM:{}";
private final String RESPONSE = "RESPONSE URL:{},RESPONSE METHOD:{},RESPONSE PARAM:{}";
/**
* 拦截controller
*/
@Pointcut("within(com.ztocc.tms.operates.controller..*)")
public void requestAspect() {
}
@Before(value = "requestAspect()")
public void methodBefore(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info(REQUEST, request.getRequestURI(), request.getMethod(),
JSON.toJSONString(Arrays.toString(joinPoint.getArgs())));
}
@AfterReturning(returning = "o", pointcut = "requestAspect()")
public void methodAfter(Object o) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info(RESPONSE, request.getRequestURI(), request.getMethod(),
JSONObject.toJSONString(o));
}
}