Serilog的其他属性 [英] Serilog Additional Properties
问题描述
我使用Serilog并将事件记录到SQL Server(使用Serilog,Serilog.Framework.Logging和Serilog.Sinks.MSSqlServer库).
I work working with Serilog and logging events to SQL Server (using the Serilog, Serilog.Framework.Logging and Serilog.Sinks.MSSqlServer libraries).
作为MVC6应用程序的一部分,当我记录事件并设置选项以包括属性时,我会在XML列中看到一些其他属性.
As part of an MVC6 application, when I log events and set the option to include properties, I see some additional properties in the XML column.
如果我发出类似以下声明的内容:
If I issue something like the following statement:
Log.Information("{Property1}", "Value1");
我在属性"列中看到以下内容:
I see something like the following in the Properties column:
<properties>
<property key="Property1">Value1</property>
<property key="SourceContext">WebApplication4.Controllers.BaseController</property>
<property key="ActionId">1b9f9c7e-7c5c-4b14-a30d-99f2ebc88c51</property>
<property key="RequestId">80000191-0001-f000-b63f-84710c7967bb</property>
</properties>
这些额外的属性从何而来?我可以设置类似于这些的其他属性吗?如果是这样,我应该在哪里设置它们?如果我将其他属性包含在消息中,则可以设置它们(类似于上面的Property1),但是我可能想包括消息中没有的其他属性.
Where do these extra properties come from? Can I set additional properties similar to these? If so, where do I set them? I can set additional properties if I include them in the message (similar to Property1 above) but I might want to include additional properties that are not in the message.
推荐答案
有三种解决方法.
首先是使用ForContext()
创建附加了特定属性的记录器实例:
The first is to use ForContext()
to create a logger instance with specific properties attached:
var specific = Log.ForContext("SomeProperty", 42);
specific.Information("This has properties attached");
第二个是使用浓缩器:
Log.Logger = new LoggerConfiguration()
.Enrich.WithMachineName()
// Other config...
第三个是LogContext
.
using (LogContext.PushProperty("SomeProperty", 42))
{
Log.Information("This has properties attached");
}
为此需要一些较小的设置,请查看 Serilog Wiki 上的信息.
Some minor setup is required for this, check out the info on the Serilog wiki.
这篇关于Serilog的其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!