SpringBoot项目中使用Aspect实现日志切面

前言#

仔代码检视时,讨论到在controller层手动添加日志太麻烦,于是想要注解和切面实现日志的自动输出,简化代码、简练程序

 

利用Aspect实现日志切面#

1、添加aop依赖#

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 

2、定义注解作为切点#

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface log {
    String value() default "";
}

 

3、声明切面,完成日志记录#

复制代码
@Aspect  // 使用@Aspect注解声明一个切面
@Component
@Slf4j
public class LogAspect {

    private static final String START = "start";
    private static final String END = "end";

    @Pointcut("@annotation(com.zh.live.aspect.log)")
    public void logPointCut() {}


    @Before("logPointCut()") //前置通知
    public void before(JoinPoint point) throws Throwable {
        try {
            printLog(point,START);
        } catch (Exception e) {
        }
    }

    @After("logPointCut()") //后置通知
    public void after(JoinPoint point) throws Throwable {
        try {
            printLog(point,END);
        } catch (Exception e) {
        }
    }

    private void printLog(JoinPoint joinPoint, String type) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String beginTime = dateFormat.format(new Date());
        //请求的 类名、方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //打印日志
        log.info("{} {} {} | time: {} param: {} " , className,methodName,type,beginTime,args);

    }

}
复制代码

 

4、在controller中需要添加日志的方法上添加@log注解#

@log
    @PostMapping("/registerUser")
    public R registerUser(@RequestBody UserTo user) 

 

5、postman发送请求进行测试#

 

至此,日志切面就完全结束了,我这里写的比较简单,大家也可以任意扩展

 

posted @   青岑  阅读(933)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示
主题色彩