如何在拦截器中获取控制器类名称以进行日志记录

时间:2019-03-18 12:26:20

标签: java spring-boot spring-mvc logging

在我的springboot应用程序中,我们正在使用org.springframework.web.util.ContentCachingRequestWrapperorg.springframework.web.util.ContentCachingResponseWrapper记录控制器的请求/响应。请参阅下面的链接以获取示例代码。

CustomLoggingFilter:

  

https://stackoverflow.com/a/42023374/1958669

应用程序中存在interceptor。现在的问题是,仅记录其在className中的拦截器名称。因此,为了获取实际的控制器名称,我尝试在拦截器中获取类名称。但这给出了org.springframework.web.util.ContentCachingRequestWrapper

CustomWebMvcConfig:

@Configuration
public class CustomWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomLogInterceptor());
    }
}

CustomLogInterceptor:

public class CustomLogInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LogManager.getLogger(CustomLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{
        //Some operation
    }
}

以以下格式获取日志:

  

time =“ 2019-03-18T09:59:51,001Z”,线程=“ [o-auto-1exec-]”,class =“ a.b.c.CustomLoggingFilter”,message =“ Payload_1”

     

time =“ 2019-03-18T09:59:51,001Z”,thread =“ [o-auto-1-xec-1]”,class =“ abcCustomLoggingFilter“,message =” Payload_2“”

我的问题是如何在日志中获取实际的ControllerClass名称,而不是LoggingFilterClass(使用org.springframework.web.util.ContentCachingRequestWrapper的那个)

1 个答案:

答案 0 :(得分:1)

您可以尝试:

HandlerMethod handlerMethod = (HandlerMethod) handler;
String controllerName = handlerMethod.getBeanType().getSimpleName().replace("Controller", "");

或者如果您要打印URI:

request.getRequestURI();

我认为您无法更改记录器,因为您不知道谁将成为控制者。