【问题标题】:how to get controller class name in interceptors for logging如何在拦截器中获取控制器类名以进行日志记录
【发布时间】:2019-08-08 19:44:21
【问题描述】:

在我的 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());
    }
}

自定义日志拦截器:

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", thread="[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 的名称)

【问题讨论】:

  • 你这样做的目的是什么?
  • 我正在获取以下格式的日志,即类名始终是 CustomLoggingFilter ,而应该是实际的控制器名称。 time="2019-03-18T09:59:51,001Z",thread="[o-auto-1-exec-1]",class=“a.b.c.CustomLoggingFilter ",message=“Payload_1“ time="2019-03-18T09:59:51,001Z",thread="[o-auto-1-exec-1]",class=“a.b.c.CustomLoggingFilter ",message=“Payload_2“
  • 你打算用它来记录日志吗?
  • 是的,仅用于记录。
  • 那么我建议你最好的办法是使用一个方面来做你想做的事。

标签: java spring-boot spring-mvc logging


【解决方案1】:

你可以试试:

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

或者如果你想打印 URI:

request.getRequestURI();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    相关资源
    最近更新 更多