'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 1:[1]
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();
Solution 2:[2]
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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sheltem |
| Solution 2 | akamuza |
