[英]ASP.NET Core Serilog not pushing property to its custom column
我在appsettings.json
安裝了appsettings.json
用於我的Serilog安裝的設置
"Serilog": {
"MinimumLevel": "Information",
"Enrich": [ "LogUserName" ],
"Override": {
"Microsoft": "Critical"
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "Server=.\\SQLEXPRESS;Database=Apple;Trusted_Connection=True;MultipleActiveResultSets=true;,
"schemaName": "Apple",
"tableName": "EventLogs",
"columnOptionsSection": {
"customColumns": [
{
"ColumnName": "UserName",
"DataType": "nvarchar",
"DataLength": 256,
"AllowNull": true
}
]
}
}
}
]
},
我還有一個名為LogUserName
的自定義LogUserName
,它應該將用戶用戶名添加到db中名為UserName
的列中。
這是更豐富的:
public class LogUserName
{
private readonly RequestDelegate next;
public LogUserName(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
LogContext.PushProperty("UserName", context.User.Identity.Name);
await next(context);
//return next(context);
}
}
我已將.Enrich.FromLogContext()
添加到我的Program.cs
。
到目前為止,我能夠在屬性標記中看到UserName
,但我無法將其推送到列。
編輯:
我將此模型用於我的日志到數據庫:
public class EventLogs
{
[Key]
public int Id { get; set; }
public string Level { get; set; }
public DateTime TimeStamp { get; set; }
public string UserName { get; set; }
public string Properties { get; set; }
public string LogEvent { get; set; }
public string Exception { get; set; }
public string Message { get; set; }
public string MessageTemplate { get; set; }
}
您的濃縮器無效。 你混淆了兩個概念。 將屬性添加到日志上下文與創建實際的richr不同。 實際的richr應該實現ILogEventEnricher,如本例所示。
您實際創建的是ASP.NET中間件。 LogContext.PushProprety返回一個IDisposable,應該包含在using語句中,然后using語句塊中的任何內容都應該具有帶有附加屬性的日志上下文。 如文檔中所示。
解決此問題的一種方法是從您的LogUserName
配置中刪除LogUserName
。 然后將您的中間件更改為:
public class LogUserNameMiddleware
{
private readonly RequestDelegate next;
public LogUserNameMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
using(LogContext.PushProperty("UserName", context.User.Identity.Name))
{
await next(context);
}
}
}
請注意,如果您還沒有這樣做,您需要告訴ASP.NET Core有關中間件的信息。
public static class LogUserNameMiddlewareExtensions
{
public static IApplicationBuilder UseLogUserNameMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<LogUserNameMiddleware>();
}
}
在Startup.Configure方法中,您可以將中間件添加到管道中:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseLogUserNameMiddleware();
//your other middleware
}
}
注意,如果沒有登錄用戶,您可能希望清理中間件以進行處理,因此您不會收到NullReferenceException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.