简体   繁体   中英

Logging not working in web application using Spring AOP

using Spring AOP, I'm trying to put logging in my web application for an object called corelation like below :-

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 {}

In my main REST Controller operation, using @Correlated annotation, I'm trying to log this corellation like below :-

  @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
----
---
}

However, when I test my service using PostMan tool and see the applicaiton logs, the corelation id is never logged :-

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

Please advise is this a configuration issue in Spring AOP.

Thanks

This can get working in either of below two ways

  1. Provide fully qualified name of Correlated in the pointcut definition as @Around("@annotation(com.xyzCorrelated)")
  2. Update the Aspect method signature to include the Correlated as second argument

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

Let know in comments if anything else is required.

PS : Also as pointed out by M. Deinum make sure to remove object cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM