Search code examples
javarestspring-bootaspectj

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.


Solution

  • 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();