[英]Populate custom columns in Serilog MsSql sink
我在我的 dotnet 核心應用程序中使用 Serilog。 我已將自定義列添加到 Serilog 提供的默認列列表中。 下面是我的“Serilog”配置在 appsettings.json 文件中的樣子 -
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": <connectionString>
"tableName": "Log",
"autoCreateSqlTable": true,
"columnOptionsSection": {
"removeStandardColumns": [ "MessageTemplate", "Properties"], //remove the Properties column in the standard ones
"customColumns": [
{
"ColumnName": "ControllerName",
"DataType": "varchar",
"DataLength": 50
}
]
},
"timeStamp": {
"columnName": "Timestamp",
"convertToUtc": true
}
}
}
]
}
因此,我從 Serilog 創建的默認列列表中刪除了“MessageTemplate”和“Properties”,並將“ControllerName”作為新列添加到表Log中,Serilog 在其中記錄其數據。 我想要的是,當我記錄信息時,我想為“ControllerName”列提供值。 怎么做到呢? 我找到了以下解決方案:
_logger.LogInformation("{ControllerName}{Message}", "TestController", "Starting up..");
這行代碼為 ControllerName 列提供了值,但消息列將值作為
"TestController""Starting up.."
我希望消息列獲得值
Starting up..
您似乎使用的是 Microsoft 的ILogger<T>
而不是 Serilog 的ILogger
,因此為了添加將包含在日志事件中而不是消息的一部分的上下文屬性,您必須使用BeginScope
創建一個新的日志記錄范圍,例如
using (_logger.BeginScope("{ControllerName}", nameof(TestController)))
{
_logger.LogInformation("{Message}", "Starting up...");
}
另一種選擇是向 Serilog 的LogContext
添加一個屬性:
using (LogContext.PushProperty("ControllerName", nameof(TestController))
{
_logger.LogInformation("{Message}", "Starting up...");
}
這將為您提供與上述BeginScope
相同的最終結果,但它是特定於 Serilog 的 API,並且首先違背了使用ILogger<T>
的目的,因此除非您決定改用 Serilog 的ILogger
,否則BeginScope
將是首選.
一項重要的觀察是,為了使LogContext
工作,您需要在配置記錄器時啟用它。 例如:
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext() // <<<<<<<<<<#############
.WriteTo.Console()
.CreateLogger();
如果您要使用 Serilog 的ILogger
,那么除了能夠使用LogContext
,您還可以使用Log.ForContext
創建一個新的上下文:
var contextLogger = logger.ForContext("ControllerName", nameof(TestController));
contextLogger.Information("{Message}", "Starting up...");
ps:如果您不確定是否應該使用微軟的ILogger<T>
或 Serilog 的ILogger
,我建議閱讀這個答案: Serilog DI in ASP.NET Core, which ILogger interface to injection?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.