问题描述
应用程序应在不影响客户端的情况下(在单独的线程中)异步记录以下信息.
The application should log the following information without impacting a client, asynchronously(in a separate thread).
- 请求HTTP方法和URI
- 请求标头(默认值除外)
- 客户的IP地址
- 请求处理时间(以毫秒为单位)
- 请求正文
- 响应正文
如果我们在过滤器中使用inputstream
,那么spring不能再次使用它来将json映射到对象.在输入流到对象映射期间的某个地方,我们可以插入记录器吗?
If we consume inputstream
in the filter, then it cant be consumed again by spring for json to object mapping. Somewhere during the input stream to object mapping, can we plug our logger?
更新:
我们可以在 MessageConverter 中重写日志记录代码,但这似乎不是一个好方法想法.
We can write over logging code in a MessageConverter, but it doesnt seems to be a good idea.
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));
}
}
推荐答案
来自 baeldung.com的答案:
- CommonsRequestLoggingFilter
- ServletContextRequestLoggingFilter
可以通过添加bean定义来配置Spring Boot应用程序以启用请求 记录:
Spring Boot application can be configured by adding a bean definition to enable request logging:
@Configuration
public class RequestLoggingFilterConfig {
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter
= new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
filter.setAfterMessagePrefix("REQUEST DATA : ");
return filter;
}
}
此外,此日志记录过滤器要求将日志级别设置为DEBUG.在 application.properties
放置
Also, this logging filter requires the log level be set to DEBUG. In application.properties
put
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
要使日志记录异步,我们可以使用异步附加程序.不幸的是,它不支持日志记录响应有效负载. :(
To make the logging asynchronous, we may use asynchronous appenders. Unfortunately it does not support logging response payloads. :(
这篇关于如何在Spring Rest中记录所有请求响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!