request log add stringfield length
This commit is contained in:
@@ -11,4 +11,9 @@ public class SimApiRequestLogOptions
|
|||||||
/// 是否打印完整的响应体
|
/// 是否打印完整的响应体
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool ShowFullResponse { get; set; }
|
public bool ShowFullResponse { get; set; }
|
||||||
}
|
|
||||||
|
/// <summary>
|
||||||
|
/// 请求字段显示最长长度
|
||||||
|
/// </summary>
|
||||||
|
public int RequestStringLogLength { get; set; } = 0;
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Middlewares;
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
@@ -53,7 +54,25 @@ public class SimApiRequestLogMiddleware(
|
|||||||
var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync();
|
var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync();
|
||||||
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
||||||
logMessage.AppendLine("*( RequestBody ) =>");
|
logMessage.AppendLine("*( RequestBody ) =>");
|
||||||
logMessage.AppendLine(requestBodyText);
|
if (options.RequestStringLogLength == 0)
|
||||||
|
{
|
||||||
|
logMessage.AppendLine(requestBodyText);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var reqLogs = SimApiUtil.FromJson<Dictionary<string, object>>(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;
|
var originalBodyStream = context.Response.Body;
|
||||||
using var responseBody = new MemoryStream();
|
using var responseBody = new MemoryStream();
|
||||||
@@ -102,4 +121,4 @@ public class SimApiRequestLogMiddleware(
|
|||||||
|
|
||||||
edi?.Throw();
|
edi?.Throw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user