比如下面的 LogError 日志代码,requestBody 中的所有双引号都被转义为 \"
,影响了日志消息的可读性
var requestBody = response.RequestMessage?.Content != null ?
"\n" + await response.RequestMessage.Content.ReadAsStringAsync(cancellationToken) :
string.Empty;
_logger.LogError(
"Failed to request {requestUri}. Status code is {statusCode}. {requestBody}",
response.RequestMessage?.RequestUri,
(int)response.StatusCode,
requestBody);
日志消息输出
"{\"url\":\"https://www.cnblogs.com/dudu/\",\"presetName\":\"snapshot\",\"args\":[[\"snapshots/0/1\",\"\",\"\"]]}"
原来是 serilog 的配置问题,将 outputTemplate 中的 {Message}
改为 {Message:l}
就可以了
{
"Serilog": {
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Cnblogs": "Information"
}
},
"WriteTo":[
{
"Name": "File",
"Args": {
"path": "logs/log-.log",
"rollingInterval": "Day",
"retainedFileCountLimit": "3",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message:l}{NewLine}{RequestPath}{NewLine}{SourceContext}{NewLine}{Exception}"
}
}
]
}
}
与这个问题类似:How to log objects as json with JsonConsole in .NET 6 without escaping
– dudu 1年前