相关疑难解决方法(0)

如何在Spring Rest中记录所有请求-响应?

应用程序应在不影响客户端的情况下(在单独的线程中)异步记录以下信息。

  • 请求HTTP方法和URI
  • 请求标头(默认值除外)
  • 客户端的IP地址
  • 请求处理时间(以毫秒为单位)
  • 请求正文
  • 反应体

如果我们inputstream在过滤器中使用,那么spring不能再次使用它来将json映射到对象。在输入流到对象映射的某个地方,我们可以插入记录器吗?

更新:

我们可以在MessageConverter中重写日志记录代码,但这似乎不是一个好主意。

public class MyMappingJackson2MessageConverter extends AbstractHttpMessageConverter<Object> {
    ...
    protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        InputStream inputStream = inputMessage.getBody();
        String requestBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        String method = request.getMethod();
        String uri = request.getRequestURI();
        LOGGER.debug("{} {}", method, uri);
        LOGGER.debug("{}", requestBody);
        return objectMapper.readValue(requestBody, clazz);
    }

    protected void writeInternal(Object o, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        String responseBody = objectMapper.writeValueAsString(o);
        LOGGER.debug("{}", responseBody);
        outputMessage.getBody().write(responseBody.getBytes(StandardCharsets.UTF_8));
    }
}
Run Code Online (Sandbox Code Playgroud)

rest logging spring spring-boot

5
推荐指数
2
解决办法
1万
查看次数

标签 统计

logging ×1

rest ×1

spring ×1

spring-boot ×1