Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 552
MABC Avatar asked Dec 14 '22 22:12

MABC


2 Answers

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();
like image 122
sheltem Avatar answered Dec 31 '22 07:12

sheltem


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());
like image 25
akamuza Avatar answered Dec 31 '22 06:12

akamuza