【问题标题】:Logging not working in web application using Spring AOP使用 Spring AOP 无法在 Web 应用程序中进行日志记录
【发布时间】:2019-03-09 09:59:22
【问题描述】:

使用 Spring AOP,我正在尝试将日志记录到我的 Web 应用程序中,以获取一个名为 corelation 的对象,如下所示:-

LoggingCorrelationEnrichingAspect.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());
    }
}

Correlated.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 工具测试我的服务并查看应用程序日志时,永远不会记录关联 ID:-

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

请告知这是 Spring AOP 中的配置问题。

谢谢

【问题讨论】:

  • 第一个方法参数不是Map,而是UUID。此外,在您的方面,您不应该转换为 Mono,您应该只返回 proceedingJoinPoint.proceed() 的结果。
  • 谢谢,我尝试了您的建议,但现在仍然有效。任何想法
  • 切面是否被调用了?我实际上怀疑它是否会被调用,您的应用程序会因ClassCastException 而崩溃,说明UUID 不能转换为Map。
  • 不确定,但我认为它应该调用,因为我在 Restcontroller 中使用 @Correlated 注释了我的方法操作.....请建议

标签: spring spring-mvc spring-boot logging spring-aop


【解决方案1】:

这可以通过以下两种方式之一发挥作用

  1. 在切入点定义中提供Correlated 的完全限定名称@Around("@annotation(com.x.y.z.Correlated)")
  2. 更新 Aspect 方法签名以包含 Correlated 作为第二个参数

    @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());
    }
    

如果需要其他任何内容,请在 cmets 中告知。

P.S.:正如 M. Deinum 所指出的,请确保移除对象投射。

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多