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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With