Spring Boot中使用log4j实现http请求日志入mongodb
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class LogRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOGGER = LogManager.getLogger();
@Autowired
private Environment env;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// 记录请求的详细信息
LOGGER.info("请求方法: {}", request.getMethod());
LOGGER.info("请求URL: {}", request.getURI());
LOGGER.info("请求体: {}", new String(body));
// 发起请求并获取响应
ClientHttpResponse response = execution.execute(request, body);
// 记录响应的详细信息
LOGGER.info("响应状态码: {}", response.getStatusCode());
LOGGER.info("响应头: {}", response.getHeaders());
// 将日志信息保存到MongoDB
// 此处省略将日志信息保存到MongoDB的代码
return response;
}
}
这段代码定义了一个LogRequestInterceptor
类,实现了ClientHttpRequestInterceptor
接口。它会在发送每个HTTP请求前后记录详细的日志信息,并将这些信息保存到MongoDB。这个例子省略了将日志信息保存到MongoDB的代码,你需要根据实际情况实现这部分。
评论已关闭