首页  >  文章  >  Java  >  用于日志记录的 Spring AOP

用于日志记录的 Spring AOP

Barbara Streisand
Barbara Streisand原创
2024-10-22 20:44:02524浏览

Spring AOP pour la journalisation

AOP(面向方面​​编程)是一种允许业务代码与技术代码分离的编程范例。这种范例在某种程度上被许多开发人员忽视,但却是一个非常强大的工具。
在本教程中,我们将尝试使用 Spring Boot 3 来应用此范例来记录我们的服务。

先决条件

  • JDK 17
  • IDE
  • maven 3.x

要添加的依赖项

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>3.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

LoggingAspect.java
这个类将包含我们用于日志记录的 AOP:

package dev.tuxbe.democonfig.contracts;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class LoggingAspect {

    @Pointcut("execution(* dev.tuxbe.democonfig.services.*.*(..))")
    public void serviceMethods() {
    }

    @Before("serviceMethods()")
    public void logBeforeServiceMethods(JoinPoint joinpoint) {
        String name = joinpoint.getSignature().getName();
        log.info("Début de traitement de la method {} avec pour parametre {}", name, joinpoint.getArgs());
    }

    @AfterReturning(value = "serviceMethods()", returning = "proceed")
    public void logAfterReturningServiceMethods(JoinPoint joinpoint, Object proceed) {
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();

        // Logiquement, si nous atteignons ce point, le traitement s'est bien terminé
        log.info("Méthode {} exécutée avec succès avec les arguments {}", methodName, args);
        log.info("Résultat : {}", proceed);
    }

    @AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
    public void logAfterThrowingServiceMethods(JoinPoint joinPoint, Throwable ex) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        // Récupérer la requête HTTP
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String uri = request.getRequestURI();
        String method = request.getMethod();

        // Logiquement, si nous atteignons ce point, une exception a été levée pendant l'exécution de la méthode
        log.info("{} : {} exécutée avec echec avec les arguments {}",method, uri, args);
        log.info("Message d'error : {}", ex.getMessage());
    }
}

  • @Pointcut() 允许您在每次调用 dev.tuxbe.democonfig.services 包中找到的方法时标记一个监听点。
  • @Before("serviceMethods()")注释的方法在执行你正在监听的服务之前调用
  • AfterThrowing() 注解的方法,每次在监听的服务执行过程中检测到错误时都会执行。
  • AfterReturning() 注解的方法在服务执行完成且没有错误的情况下执行

这种日志记录技术可以帮助您拥有可维护且干净的代码吗?

以上是用于日志记录的 Spring AOP的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn