应用程序应在不影响客户端的情况下异步记录以下信息(在单独的线程中)。
- 请求 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));
}
}
原文由 Nilesh 发布,翻译遵循 CC BY-SA 4.0 许可协议
来自 baeldung.com 的回答:
为了使日志记录异步,我们可以使用 异步 appenders 。不幸的是,它不支持记录响应负载。 :(