在SpringBoot中重用HTTP请求响应体(实现请求响应日志的记录)

缓存请求响应体的目的

把一个HTTP的请求,响应信息完整的纪录到日志。是一种常见有效的问题排查,BUG重现的手段。

但是这种东西,有一个特点就是只能读取/写入一次,不能重复。下一次读写,就是一个空的流,为了实现流的重用,就很有必要,把读取和写入的数据缓存起来, 可以在某个地方,再一次的读取。

实现的思路

  • HttpServletRequestWrapper
  • HttpServletResponseWrapper

上面2个类,熟悉Servlet的都知道,这俩就是RequestResponse的装饰模式实现。

通过装饰者设计模式,我们可以在Request读取请求body的时候,把读取到的数据复制一份缓存起来,记录日志时使用。同理,也可以把Response响应的数据,先缓存起来,用于记录日志,然后再响应给客户端。

Spring提供的实现

ContentCachingRequestWrapper

// 这里忽略了 HttpServletRequest 的相关方法
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper  {
	// 包装Servlet,不限制请求体的大小
	public ContentCachingRequestWrapper(HttpServletRequest request)
	// 包装Servlet,限制请求体的大小
	public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit)
	// 获取到缓存的请求体
	public byte[] getContentAsByteArray()
	// 请求体超过限制时会调用这个方法,默认空实现
	protected void handleContentOverflow(int contentCacheLimit) 
}

比较好理解的一个类,建议通过contentCacheLimit限制请求体大小。因为它默认把请求体缓存到内存中,如果客户端发起恶意请求,构造大体积的请求体可能会消耗干净服务器的内存

ContentCachingResponseWrapper

// 这里忽略了 HttpServletResponse 的相关方法
public class ContentCachingResponseWrapper {
	// 把缓存中的响应数据,刷出到客户端
	void copyBodyToResponse()
	// 获取缓存数据
	byte[] getContentAsByteArray()
	// 获取缓存数据
	InputStream getContentInputStream()
	// 获取缓存数据的大小
	int getContentSize()
}

很简单,通过ContentCachingResponseWrapper 的包装,任何往客户端的响应数据,都会被它缓存起来,重复的读取使用,最终响应给客户端

请求日志的实现

Controller

及其简单,把请求体,添加时间戳后回写给客户端。

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/demo")
public class DemoController {
	
	@RequestMapping(produces = { "application/json; charset=utf-8" })
	public Object demo (@RequestBody(required = false) String body) {
		Map<String, Object> response = new HashMap<>();
		response.put("reqeustBody", body);
		response.put("timesttamp", System.currentTimeMillis());
		return response;
	}
}

AccessLogFilter

通过AccessLogFilter输出请求体/响应体,耗时,等等信息到日志。还对当前请求体生成了一个全局唯一request-id,可以作为检索的条件。

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.NestedServletException;

@Component
@WebFilter(filterName = "accessLogFilter", urlPatterns = "/*")
@Order(-9999) 		// 保证最先执行
public class AccessLogFilter extends HttpFilter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AccessLogFilter.class);
	
	private static final long serialVersionUID = -7791168563871425753L;
	
	// 消息体过大
	@SuppressWarnings("unused")
	private static class PayloadTooLargeException extends RuntimeException {
		private static final long serialVersionUID = 3273651429076015456L;
		private final int maxBodySize;
		public PayloadTooLargeException(int maxBodySize) {
			super();
			this.maxBodySize = maxBodySize;
		}
	}

	@Override
	protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
		
		ContentCachingRequestWrapper cachingRequestWrapper = new ContentCachingRequestWrapper(req, 30) { // 限制30个字节
			@Override
			protected void handleContentOverflow(int contentCacheLimit) {
				throw new PayloadTooLargeException(contentCacheLimit);
			}
		};
		
		ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(res);
		
		
		long start = System.currentTimeMillis();
		try {
			// 执行请求链
			super.doFilter(cachingRequestWrapper, cachingResponseWrapper, chain);
		} catch (NestedServletException e) {
			Throwable cause = e.getCause();
			// 请求体超过限制,以文本形式给客户端响应异常信息提示
			if (cause instanceof PayloadTooLargeException) {
				cachingResponseWrapper.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
				cachingResponseWrapper.setContentType(MediaType.TEXT_PLAIN_VALUE);
				cachingResponseWrapper.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
				cachingResponseWrapper.getOutputStream().write("请求体过大".getBytes(StandardCharsets.UTF_8));
			} else {
				throw new RuntimeException(e);
			}
		}
		
		long end = System.currentTimeMillis();
		
		String requestId = UUID.randomUUID().toString();		// 生成唯一的请求ID
		cachingResponseWrapper.setHeader("x-request-id", requestId);
		
		String requestUri = req.getRequestURI();		// 请求的
		String queryParam = req.getQueryString();		// 查询参数
		String method = req.getMethod();				// 请求方法
		int status = cachingResponseWrapper.getStatus();// 响应状态码
		
		// 请求体
		// 转换为字符串,在限制请求体大小的情况下,因为字节数据不完整,这里可能乱码,
		String requestBody = new String(cachingRequestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);	
		// 响应体
		String responseBody = new String(cachingResponseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
		
		LOGGER.info("{} {}ms", requestId, end - start);
		LOGGER.info("{} {} {} {}", method, requestUri, queryParam, status);
		LOGGER.info("{}", requestBody);
		LOGGER.info("{}", responseBody);
		
		// 这一步很重要,把缓存的响应内容,输出到客户端
		cachingResponseWrapper.copyBodyToResponse();
	}
}

演示

正常请求和日志

com.demo.web.filter.AccessLogFilter      : a53500bc-c003-414a-9add-99655295a34f 1ms
com.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 200
com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}
com.demo.web.filter.AccessLogFilter      : {"reqeustBody":"{\"name\": \"springboot\"}","timesttamp":1620395056498}

体积超过限制的请求和日志

com.demo.web.filter.AccessLogFilter      : 99476161-1790-48cc-86b9-0641efadc1b5 1ms
com.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 413
com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}{"name":
com.demo.web.filter.AccessLogFilter      : 请求体过大

因为限制了请求体的大小,这里日志中输出的请求体日志,就只有限制字节的大小了