简体   繁体   English

使用Spring AspectJ记录REST资源URL

[英]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. 我正在使用Spring Boot开发REST API,我想使用Spring Aspect记录客户端检索的资源的URL。 My class for the Aspect have this code: 我的Aspect类具有以下代码:

@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. 我不知道如何传递RequestMapping对象作为建议的参数,并获取URL的路径。

You can let Spring inject the client's request into your aspect: 您可以让Spring将客户端的请求注入您的方面:

@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: 然后可以通过以下方法从before方法中检索客户端调用的原始URL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM