问题
I work working with Serilog and logging events to SQL Server (using the Serilog, Serilog.Framework.Logging and Serilog.Sinks.MSSqlServer libraries).
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>
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.
回答1:
There are three ways to go about this.
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");
The second is using enrichers:
Log.Logger = new LoggerConfiguration()
.Enrich.WithMachineName()
// Other config...
The third is the LogContext
.
using (LogContext.PushProperty("SomeProperty", 42))
{
Log.Information("This has properties attached");
}
Some minor setup is required for this, check out the info on the Serilog wiki.
来源:https://stackoverflow.com/questions/32974560/serilog-additional-properties