SpringBoot + AOP + 自定义注解实现统一日志处理

爱被打了一巴掌 2023-07-24 09:25 86阅读 0赞

SpringBoot + AOP + 自定义注解实现统一日志处理

在实际开发中,我们经常需要对接口方法打印出日志,比如参数等。如果每个方法里都要手动去写,那样代码显得太冗余了,而且日志风格也参差不齐。
本文将使用Spring Boot、Spring AOP结合自定义注解,实现统一的日志处理。

添加依赖

因为我将会使用json序列化,所以加入了fastjson的依赖.

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.projectlombok</groupId>
  11. <artifactId>lombok</artifactId>
  12. <optional>true</optional>
  13. </dependency>
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>fastjson</artifactId>
  17. <version>1.2.47</version>
  18. </dependency>

主启动类

如果使用Spring Initializr生成项目,则无须手动编写。

  1. @SpringBootApplication
  2. public class SpringBootAopApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(SpringBootAopApplication.class, args);
  5. }
  6. }

编写注解

  1. @Retention(RetentionPolicy.RUNTIME) // 运行时有效
  2. @Target(ElementType.METHOD) // 定义在方法上
  3. @Documented
  4. public @interface ShowLog {
  5. String value() default "";
  6. }

编写Aspect

使用@Aspect注解声明是一个切面,并且使用@Component注解加入到IoC容器中。

  1. @Aspect
  2. @Component
  3. @Slf4j
  4. public class AnnotationLogAspect {
  5. @Pointcut("execution(public * com.xudc.springboot.web.*.*(..))")
  6. public void aopLog(){
  7. }
  8. @Before("aopLog() && @annotation(showLog)")
  9. public void doBefore(JoinPoint joinPoint, ShowLog showLog) {
  10. Object[] args = joinPoint.getArgs();
  11. log.info("参数={}", JSON.toJSONString(args));
  12. Signature signature = joinPoint.getSignature();
  13. log.info("方法={}", signature.getName());
  14. ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
  15. HttpServletRequest request = attributes.getRequest();
  16. StringBuffer url = request.getRequestURL();
  17. log.info("请求地址={}", url);
  18. Map<String, Object> params = new HashMap<>(16);
  19. request.getParameterMap().forEach((key, values) -> {
  20. if (values.length == 1) {
  21. params.put(key, values[0]);
  22. } else {
  23. params.put(key, values);
  24. }
  25. });
  26. log.info("请求参数={}", JSON.toJSONString(params));
  27. log.info("注解value={}", showLog.value());
  28. }
  29. }

编写接口

  1. @RestController
  2. public class TestController {
  3. @GetMapping("/test/{id}")
  4. @ShowLog("输出日志")
  5. public String test(@PathVariable String id, @RequestParam(required = false) String name){
  6. return "success";
  7. }
  8. }

详细代码














GitHub 码云

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读