AOP日志输出
需要通过日志记录接口调用信息。便于后期调试排查。并且可能有很多接口都需要进行日志的记录。
接口被调用时日志打印格式如下
在企业开发中大多使用的是注解+aop
@Target({ElementType.METHOD}) // 注解作用在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
public @interface SystemLog {
String businessName() default "";
}
@Aspect
@Component
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.sangeng.annotation.SystemLog)")
public void pt() {
}
@Around("pt()")
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
Object ret;// 执行方法
try {
log.info("==============Start============");
handleBefore(joinPoint);// 前置
ret = joinPoint.proceed();// 执行方法
handleAfter(ret);// 后置
} finally {
//结束后换行
log.info("==============End===============" + System.lineSeparator());
}
return ret;
}
private void handleAfter(Object ret) {
// 获取返回值
log.info("Response : {}", JSON.toJSONString(ret));
}
private void handleBefore(ProceedingJoinPoint joinPoint) {
// 获取请求对象
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
//获取被增强方法上的注解对象
SystemLog systemLog = getSystemLog(joinPoint);
// 打印请求 URL
log.info("URL : {}",request.getRequestURL());
// 打印描述信息
log.info("BusinessName : {}",systemLog.businessName() );
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
// 打印请求的 IP
log.info("IP : {}",request.getRemoteHost());
// 打印请求入参
log.info("Request Args : {}", JSON.toJSONString(joinPoint.getArgs()));
}
private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
SystemLog annotation = methodSignature.getMethod().getAnnotation(SystemLog.class);
return annotation;
}
}
使用时在需要输出日志的方法中添加@SystemLog(businessName = “”)
@PutMapping("userInfo")
@SystemLog(businessName = "更新个人信息")
public ResponseResult updateUserInfo(@RequestBody SysUser user){
return userService.updateUserInfo(user);
}