Spring应用中,后台需要拿到前端的请求参数,方便调试问题,一般都是使用Aop进行日志输出,但是在格式错误的时候就没有日志了。本文提供了
LoggableFilter
可以在参数转换之前就输出请求参数。
问题
Spring应用中,一般使用Aop进行请求参数和返回值的日志输出,但是这里有一个前提,就是用户请求的参数一定好可以转换为方法参数,但是经常前端请求是一个错误的Json格式,参数转换失败,并不会进入AOP所以也就看不到请求参数。只会看到org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error
。这就导致定位问题比较困难,所以后台需要一个更好的办法来输出请求参数。
难点:如果直接把HttpServletRequest
中的InputStream读取后输出日志,会导致后续业务逻辑读取不到InputStream中的内容,因为流只能读取一次。
参数输出类LoggableFilter
代码语言:javascript复制/**
* @author tenmao
* @since 2020/11/19
*/
@Slf4j
@Component
public class LoggableFilter extends HttpFilter {
@Value("${httpLog.enabled:false}")
private boolean httpLogEnabled;
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (!httpLogEnabled) {
filterChain.doFilter(request, response);
return;
}
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
try {
filterChain.doFilter(requestWrapper, responseWrapper);
} finally {
try {
HttpRequestLog requestLog = HttpRequestLog.build(requestWrapper);
HttpResponseLog responseLog = HttpResponseLog.build(responseWrapper);
log.info("Http Request: {}nnHttp Response: {}", requestLog.toMultiLines(), responseLog.toMultiLines());
} catch (Exception e) {
log.warn("fail to build http log", e);
} finally {
//这一行必须添加,否则就一直不返回
responseWrapper.copyBodyToResponse();
}
}
}
@Data
@Builder
private static class HttpRequestLog {
private String clientIp;
private String method;
private String uri;
private Map<String, String[]> parameters;
private Map<String, String> headers;
private String body;
public String toMultiLines() {
StringBuilder sb = new StringBuilder();
sb.append("n>>Start Http Requestn");
sb.append("Client IP: ").append(clientIp).append("n")
.append(method).append(" ").append(uri);
if (!CollectionUtils.isEmpty(parameters)) {
String str = parameters.entrySet().stream()
.flatMap(entry -> Arrays.stream(entry.getValue()).map(v -> Pair.of(entry.getKey(), v)))
.map(pair -> pair.getFirst() "=" pair.getSecond())
.collect(Collectors.joining("&"));
sb.append("?").append(str);
}
sb.append("n");
headers.forEach((s, s2) -> sb.append(s).append(":").append(s2).append("n"));
sb.append("n");
sb.append(body);
sb.append("n>>End Http Request");
return sb.toString();
}
public static HttpRequestLog build(ContentCachingRequestWrapper request) throws IOException {
String body = new String(request.getContentAsByteArray(), StandardCharsets.UTF_8);
String method = request.getMethod();
return HttpRequestLog.builder()
.clientIp(request.getRemoteAddr())
.method(method)
.uri(request.getRequestURI())
.parameters(request.getParameterMap())
.headers(getRequestHeaders(request))
.body(body)
.build();
}
private static Map<String, String> getRequestHeaders(HttpServletRequest request) {
Map<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.put(headerName, request.getHeader(headerName));
}
return headers;
}
}
@Data
@Builder
private static class HttpResponseLog {
private int code;
private Map<String, String> headers;
private String body;
public String toMultiLines() {
StringBuilder sb = new StringBuilder();
sb.append("n<<Start Http Responsen");
sb.append(code).append("n");
headers.forEach((s, s2) -> sb.append(s).append(":").append(s2).append("n"));
sb.append("n");
sb.append(body);
sb.append("n<<End Http Response");
return sb.toString();
}
public static HttpResponseLog build(ContentCachingResponseWrapper responseWrapper) throws IOException {
return HttpResponseLog.builder()
.code(responseWrapper.getStatus())
.headers(getResponseHeaders(responseWrapper))
.body(new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8))
.build();
}
private static Map<String, String> getResponseHeaders(ContentCachingResponseWrapper response) {
Map<String, String> headers = new HashMap<>();
Collection<String> headerNames = response.getHeaderNames();
for (String headerName : headerNames) {
headers.put(headerName, response.getHeader(headerName));
}
return headers;
}
}
}
参考
- Spring Boot 记录 Http 请求日志