网关服务:网关accesslog输出日志requestBody限制10Mb,超过不输出

This commit is contained in:
gaoqr
2025-02-08 16:42:28 +08:00
parent e69931e8d8
commit d4a73e1cf6
@@ -59,6 +59,11 @@ import static cn.hutool.core.date.DatePattern.NORM_DATETIME_MS_FORMATTER;
@Component @Component
public class AccessLogFilter implements GlobalFilter, Ordered { public class AccessLogFilter implements GlobalFilter, Ordered {
/**
* 记录的requestBody最大值
*/
public static final int REQUEST_BODY_MAX_SIZE = 1024 * 1024 * 10;
@Resource @Resource
private CodecConfigurer codecConfigurer; private CodecConfigurer codecConfigurer;
@@ -220,9 +225,7 @@ public class AccessLogFilter implements GlobalFilter, Ordered {
Flux<? extends DataBuffer> fluxBody = Flux.from(body); Flux<? extends DataBuffer> fluxBody = Flux.from(body);
return super.writeWith(fluxBody.buffer().map(dataBuffers -> { return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
// 设置 response body 到网关日志 // 设置 response body 到网关日志
byte[] content = readContent(dataBuffers); byte[] content = readContent(dataBuffers, gatewayLog);
String responseResult = new String(content, StandardCharsets.UTF_8);
gatewayLog.setResponseBody(responseResult);
// 响应 // 响应
return bufferFactory.wrap(content); return bufferFactory.wrap(content);
@@ -272,14 +275,21 @@ public class AccessLogFilter implements GlobalFilter, Ordered {
// ========== 参考 ModifyResponseBodyGatewayFilterFactory 中的方法 ========== // ========== 参考 ModifyResponseBodyGatewayFilterFactory 中的方法 ==========
private byte[] readContent(List<? extends DataBuffer> dataBuffers) { private byte[] readContent(List<? extends DataBuffer> dataBuffers, AccessLog gatewayLog) {
// 合并多个流集合,解决返回体分段传输 // 合并多个流集合,解决返回体分段传输
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers); DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()]; int readableByteCount = join.readableByteCount();
byte[] content = new byte[readableByteCount];
join.read(content); join.read(content);
// 释放掉内存 // 释放掉内存
DataBufferUtils.release(join); DataBufferUtils.release(join);
// 超过10Mb的requestBody不做记录
if (REQUEST_BODY_MAX_SIZE >= readableByteCount) {
String responseResult = new String(content, StandardCharsets.UTF_8);
gatewayLog.setResponseBody(responseResult);
}
return content; return content;
} }