自定义注解利用AOP实现日志功能 ---> 搭建优雅的日志记录
1、日志样式展示
=======Start========
请求路径 :/log
描述信息 :访问log接口进行测试
请求方式 :GET
请求Controller的全路径以及执行方法 :com.lili.controller.LogController,log
请求IP :0:0:0:0:0:0:0:1
请求参数 :[1]
Response "success"
=========End==========
2、具体实现
2.1、引入相关依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.2、自定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SystemLog {
// 该参数表示你想描述的内容
String businessName();
}
2.3、定义切面类
@Component
@Aspect
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.lili.annotation.SystemLog)")
public void pt(){
}
@Around("pt()")
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed ;
try {
handleBefore(joinPoint);
proceed = joinPoint.proceed();
handleAfter(proceed);
} finally {
// 结束后执行
log.info("=========End=========="+System.lineSeparator());
}
return proceed;
}
private void handleAfter(Object proceed) {
log.info("Response {}",JSON.toJSONString(proceed));
}
private void handleBefore(ProceedingJoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// 获取request
assert requestAttributes != null;
HttpServletRequest request = requestAttributes.getRequest();
// 获取被增强方法上的注解
SystemLog systemLog = getSystemLog(joinPoint);
log.info("=======Start========");
// 打印请求url
log.info("请求路径 :{}",request.getRequestURI());
// 打印描述信息
log.info("描述信息 :{}",systemLog.businessName());
// 打印Http method
log.info("请求方式 :{}",request.getMethod());
// 打印调用controller的全路径以及执行方法
log.info("请求Controller的全路径以及执行方法 :{},{}",joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature)joinPoint.getSignature()).getName());
// 打印请求的ip
log.info("请求IP :{}",request.getRemoteHost());
// 打印请求入参
log.info("请求参数 :{}", JSON.toJSONString(joinPoint.getArgs()));
}
private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
SystemLog annotation = methodSignature.getMethod().getAnnotation(SystemLog.class);
return annotation;
}
}
2.4、编写controller进行测试
@RestController
public class LogController {
@SystemLog(businessName = "访问log接口进行测试")
@RequestMapping("/log")
public String log(int id){
return "success";
}
}
浏览器进行访问即可,localhost:8080/log?id=1

浙公网安备 33010602011771号