【发布时间】:2018-10-03 15:52:36
【问题描述】:
我正在尝试将用户名添加到我的日志中。文档显示了这一点:
class ThreadIdEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"ThreadId", Thread.CurrentThread.ManagedThreadId));
}
}
但是,我在其他地方读到我需要使用中间件将用户名添加到日志中。
这是我目前所拥有的:
获取当前用户用户名的中间件
public class UserNameEnricher
{
private readonly RequestDelegate next;
public UserNameEnricher(RequestDelegate next)
{
this.next = next;
}
public Task Invoke(HttpContext context)
{
LogContext.PushProperty("UserName", context.User.Identity.Name);
return next(context);
}
}
Startup.cs
app.UseAuthentication();
app.UseMiddleware<UserNameEnricher>();
程序.cs
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Filter.ByExcluding(Matching.FromSource("Microsoft"))
.Filter.ByExcluding(Matching.FromSource("System"))
.Enrich.FromLogContext()
.CreateLogger();
但是,尽管进行了所有这些配置,用户名仍然没有出现。我错过了什么?
Serilog 配置:
"Serilog": {
"MinimumLevel": "Information",
"Override": {
"Microsoft": "Critical",
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "Server=.\\SQLEXPRESS;Database=App-7661DEE4-C53F-4E49-B140-2AFAA2C85927;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=true;",
"schemaName": "App",
"tableName": "EventLogs"
}
}
]
},
【问题讨论】:
-
是的,这些都不适合我。
-
您可能需要在格式字符串的某处使用
{Properties}?您是否尝试过设置断点并检查流经和/或发送到始终具有它们的 Seq 的日志事件之一。 (见getseq.net) -
如何设置属性?
-
Properties 是已添加但未在消息中使用的属性的全部标记 - 再次,强烈建议设置 Seq 以进行本地测试以帮助您学习这些内容(有关格式化消息的文档将比我更好地向你解释属性)
标签: c# asp.net asp.net-core serilog