简体   繁体   中英

Log REST resource URL using Spring AspectJ

I am using Spring Boot to develop a REST API and I would like to log the URL of the resources being retrieved by the clients using Spring Aspect. My class for the Aspect have this code:

@Component
@Aspect
public class Logs {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void allResources() {}

    @Before("allResources()")
    public void apiRequestLog(JoinPoint jp) {    
        LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info("------------------------- o -------------------------");
        String log = jp.getSignature().getName() + " >>>";
        for (Object arg : jp.getArgs()) {
            log += "\n   ARG: " + arg;
        }
        LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info(log);

    }
}

I dont know how to pass the RequestMapping object as parameter for the advice, and get the path of the URL.

You can let Spring inject the client's request into your aspect:

@Component
@Aspect
public class Logs {
   @Autowired(required = false)
   private HttpServletRequest request;
...

The original URL called by the client can then be retrieved from that in the before-method via:

request.getRequestURL();

An alternative without autowiring:

@Around("isRestController()")
public Object logApiCall(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
    .getRequest();
    log.debug("{} {} from {}",
    request.getMethod(),
    request.getRequestURI(),
    request.getRemoteAddr());

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