gpt4 book ai didi

java - 将每个请求的请求和响应以及 session ID 保存在文本文件中,REST API Spring Boot

转载 作者:行者123 更新时间:2023-12-02 02:06:39 26 4
gpt4 key购买 nike

需要帮助通过以下方式保存 REST API 的请求和响应,

Session ID:
Request:
{
{
request header
}
{
request body
}
}
Response:
{
{
response header
}
{
response body
}
}

这不应取决于日志记录级别或任何其他与日志记录相关的概念。检查了很多类似的问题,但没有答案,谁能帮帮我,谢谢。

Spring Boot - How to log all requests and responses with exceptions in single place?

最佳答案

您可以使用 HandlerInterceptorAdapter,并在文件中写入所需的信息:

Spring provides a mechanism for configuring user-defined interceptorsto perform actions before and after web requests.

Among the Spring request interceptors, one of the noteworthyinterfaces is HandlerInterceptor, which can be used to log theincoming request by implementing the following methods:

preHandle() – this method is executed before the actual controllerservice method afterCompletion() – this method is executed after thecontroller is ready to send the response Furthermore, Spring providesthe default implementation of HandlerInterceptor interface in the formof HandlerInterceptorAdaptor class which can be extended by the user.

Let’s create our own interceptor – by extendingHandlerInterceptorAdaptor as:

@Component public class TaxiFareRequestInterceptor extends
HandlerInterceptorAdapter {

@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) {
return true;
}

@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
//
} }

http://www.baeldung.com/spring-http-logging

http://www.baeldung.com/spring-mvc-handlerinterceptor

关于java - 将每个请求的请求和响应以及 session ID 保存在文本文件中,REST API Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50667072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com