代码之家  ›  专栏  ›  技术社区  ›  Vinod Kumar

使用Spring AOP在web应用程序中记录不起作用

  •  1
  • Vinod Kumar  · 技术社区  · 6 年前

    使用Spring AOP,我尝试在我的web应用程序中为一个名为corelation的对象设置日志,如下所示:-

    LoggingCorrelationInRichingAspect日志相关。java:-

    @Aspect
    @Component
    public class LoggingCorrelationEnrichingAspect {
        private static final Logger logger = getLogger(LoggingCorrelationEnrichingAspect.class);
    
        @Around("@annotation(Correlated)")
        public Object wrapWithCorrelationContext(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
                logger.info("Entering  "+ proceedingJoinPoint.getSignature().getName() +" with Correlation Id:: "
                        + ((Map)proceedingJoinPoint.getArgs()[0]).get(CommerceConnectorConstants.HttpHeaders.CORRELATION_ID).get());
            return ((Mono<?>) proceedingJoinPoint.proceed());
        }
    }
    

    相关的。java:-

    @Inherited
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Correlated {}
    

    在我的主REST控制器操作中,使用 @Correlated

      @Correlated
      @GetMapping(path = "/products}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
      public Mono<ProductBeanResponse> getProducts(
          @RequestHeader(name = Test.HttpHeaders.TENANT_ID, required = true) UUID tId,
          @RequestHeader(name = Test.HttpHeaders.CORRELATION_ID, required = true) UUID correlationId
    ----
    ---
    }
    

    但是,当我使用PostMan工具测试服务并查看应用程序日志时,corelation id从未被记录:-

    logger.info("Entering  "+ proceedingJoinPoint.getSignature().getName() +" with Correlation Id:: "
                        + ((Map)proceedingJoinPoint.getArgs()[0]).get(CommerceConnectorConstants.HttpHeaders.CORRELATION_ID).get());
    

    谢谢

    1 回复  |  直到 6 年前
        1
  •  2
  •   Bond - Java Bond    6 年前

    这可以通过以下两种方式之一实现

    1. Correlated 在切入点定义中 @Around("@annotation(com.x.y.z.Correlated)")
    2. 更新方面方法签名以包括 作为第二个论点

      @Around("@annotation(correlated)")
      public Object wrapWithCorrelationContext(ProceedingJoinPoint proceedingJoinPoint, Correlated correlated ) throws Throwable {
          logger.info("Entering  "+ proceedingJoinPoint.getSignature().getName() +" with Correlation Id:: "
                  + ((Map)proceedingJoinPoint.getArgs()[0]).get(CommerceConnectorConstants.HttpHeaders.CORRELATION_ID).get());
      return ((Mono<?>) proceedingJoinPoint.proceed());
      }
      

    如有其他需要,请在评论中告知。

    附笔。