gpt4 book ai didi

c# - ASP.NET Core Serilog 未将属性推送到其自定义列

转载 作者:行者123 更新时间:2023-11-30 17:28:00 24 4
gpt4 key购买 nike

我在 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 的自定义增强器,它应该将用户用户名添加到数据库中名为 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; }
}

最佳答案

您的增强器无效。你混淆了两个概念。将属性添加到日志上下文与创建实际的增强器不同。实际的增强器应该实现 ILogEventEnricher,如 this example 所示。 .

您实际创建的是 ASP.NET 中间件。 LogContext.PushProprety 返回一个 IDisposable 并且应该包装在一个 using 语句中,然后 using 语句 block 内的任何内容都应该具有带有附加属性的日志上下文。如the documentation所示.

解决此问题的一种方法是从您的增强器配置中删除 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。

关于c# - ASP.NET Core Serilog 未将属性推送到其自定义列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53882617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com