将所有Spring Boot http请求记录到主日志中

时间:2017-07-11 19:18:27

标签: spring-boot spring-security spring-security-oauth2 spring-boot-actuator spring-boot-admin

我想在主spring.log中记录所有http请求,减去执行器请求,因为我想通过执行器API使Spring Boot Admin显示它们。我知道我可以配置嵌入式Tomcat of Spring Boot来记录http请求,但这些不会在执行器API或Spring Boot Admin中显示。我也意识到我可以使用默认的/trace配置,但我想要的不仅仅是过去的100个请求。

目前,我的策略是使用HandlerInterceptorAdapter来记录请求。 这里的问题是如果请求未经过身份验证,则永远不会将其发送给拦截器。

拦截器:

@Component
class HttpRequestLoggingInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestLoggingInterceptor.class)

    @Override
    void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("HTTP Request - ${request.localAddr} - \"${request.method} ${request.servletPath}\" ${response.status}")
    }

}

AuthorizationServerConfigurerAdapter:

@Configuration
@EnableAuthorizationServer
class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private HttpRequestLoggingInterceptor interceptor

    @Override
    void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.addInterceptor(interceptor)
    }

}

WebMvcConfigurerAdapter:

@Configuration
@Order
class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private HttpRequestLoggingInterceptor interceptor

    @Override
    void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).excludePathPatterns("/actuator/**")
    }
}

谢谢!

0 个答案:

没有答案