优雅的日志记录:自定义注解结合AOP实现

简介: 优雅的日志记录:自定义注解结合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

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
6天前
|
运维 Java 程序员
Spring5深入浅出篇:基于注解实现的AOP
# Spring5 AOP 深入理解:注解实现 本文介绍了基于注解的AOP编程步骤,包括原始对象、额外功能、切点和组装切面。步骤1-3旨在构建切面,与传统AOP相似。示例代码展示了如何使用`@Around`定义切面和执行逻辑。配置中,通过`@Aspect`和`@Around`注解定义切点,并在Spring配置中启用AOP自动代理。 进一步讨论了切点复用,避免重复代码以提高代码维护性。通过`@Pointcut`定义通用切点表达式,然后在多个通知中引用。此外,解释了AOP底层实现的两种动态代理方式:JDK动态代理和Cglib字节码增强,默认使用JDK,可通过配置切换到Cglib
|
5天前
|
Java
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
|
5天前
|
Java
java使用AOP切面获取请求日志并记录
java使用AOP切面获取请求日志并记录
|
6天前
|
安全
自定义注解,aop实现注解锁
自定义注解,aop实现注解锁
|
6天前
|
Java 测试技术 开发者
【亮剑】通过自定义注解实现Spring AOP,可以更灵活地控制方法拦截和增强
【4月更文挑战第30天】通过自定义注解实现Spring AOP,可以更灵活地控制方法拦截和增强。首先定义自定义注解,如`@MyCustomAnnotation`,然后创建切面类`MyCustomAspect`,使用`@Pointcut`和`@Before/@After`定义切点及通知。配置AOP代理,添加`@EnableAspectJAutoProxy`到配置类。最后,在需拦截的方法上应用自定义注解。遵循保持注解职责单一、选择合适保留策略等最佳实践,提高代码可重用性和可维护性。记得测试AOP逻辑。
|
6天前
|
存储 消息中间件 Java
Java多线程实战-异步操作日志记录解决方案(AOP+注解+多线程)
Java多线程实战-异步操作日志记录解决方案(AOP+注解+多线程)
|
6天前
|
Java 数据库连接 应用服务中间件
Spring5源码(39)-Aop事物管理简介及编程式事物实现
Spring5源码(39)-Aop事物管理简介及编程式事物实现
27 0
|
6天前
AOP&面向切面编程
AOP&面向切面编程
58 0
|
6天前
|
Java 程序员 Maven
Spring AOP入门指南:轻松掌握面向切面编程的基础知识
Spring AOP入门指南:轻松掌握面向切面编程的基础知识
|
6天前
|
数据库
AOP(面向切面编程)的基本概念和原理
AOP(面向切面编程)的基本概念和原理
99 0