From e17b9d9eedadb769f4d7f55ac3fb2f31fe219ff1 Mon Sep 17 00:00:00 2001 From: xRain Date: Tue, 11 Aug 2026 04:22:36 +0800 Subject: [PATCH] request log add stringfield length --- Configurations/SimApiRequestLogOptions.cs | 7 ++++++- Middlewares/SimApiRequestLogMiddleware.cs | 23 +++++++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/Configurations/SimApiRequestLogOptions.cs b/Configurations/SimApiRequestLogOptions.cs index b2916f7..a17e57b 100644 --- a/Configurations/SimApiRequestLogOptions.cs +++ b/Configurations/SimApiRequestLogOptions.cs @@ -11,4 +11,9 @@ public class SimApiRequestLogOptions /// 是否打印完整的响应体 /// public bool ShowFullResponse { get; set; } -} + + /// + /// 请求字段显示最长长度 + /// + public int RequestStringLogLength { get; set; } = 0; +} \ No newline at end of file diff --git a/Middlewares/SimApiRequestLogMiddleware.cs b/Middlewares/SimApiRequestLogMiddleware.cs index fed2769..4f114d6 100644 --- a/Middlewares/SimApiRequestLogMiddleware.cs +++ b/Middlewares/SimApiRequestLogMiddleware.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using SimApi.Configurations; +using SimApi.Helpers; namespace SimApi.Middlewares; @@ -53,7 +54,25 @@ public class SimApiRequestLogMiddleware( var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync(); context.Request.Body.Seek(0, SeekOrigin.Begin); logMessage.AppendLine("*( RequestBody ) =>"); - logMessage.AppendLine(requestBodyText); + if (options.RequestStringLogLength == 0) + { + logMessage.AppendLine(requestBodyText); + } + else + { + var reqLogs = SimApiUtil.FromJson>(requestBodyText); + foreach (var reqLog in reqLogs) + { + if (reqLog.Value is not JsonElement { ValueKind: JsonValueKind.String } je) continue; + var str = je.GetString(); + if (str?.Length > options.RequestStringLogLength) + { + reqLogs[reqLog.Key] = str[..options.RequestStringLogLength] + $"...({str.Length})"; + } + } + + logMessage.AppendLine(SimApiUtil.Json(reqLogs)); + } var originalBodyStream = context.Response.Body; using var responseBody = new MemoryStream(); @@ -102,4 +121,4 @@ public class SimApiRequestLogMiddleware( edi?.Throw(); } -} +} \ No newline at end of file