I am new to Serilog and I am having a hard time figuring out how to use the context functionality. When I run the code below the output file does not include the the report id. Any ideas what I am missing?

var logger = new LoggerConfiguration()
                .WriteTo
                .File(@"C:\Log.txt")
                .CreateLogger()
                .ForContext("Report ID", 10);

logger.Information("Test"); 
有帮助吗?

解决方案

Not all properties attached to a log event will be rendered by all sinks attached to the logger; the file sink used here only includes the timestamp, level, message and so-on.

To get the report ID into the file, include it in the sink's outputTemplate:

var logger = new LoggerConfiguration()
  .WriteTo.File(@"C:\Log.txt",
    outputTemplate: "{Timestamp:u} [{Level}] ({ReportId}) {Message}{NewLine}{Exception}")
  .CreateLogger()
  .ForContext("ReportId", 10);

logger.Information("Test"); 

This will include the report ID in each message.

ForContext is usually used to create a short temporary scope; if you want the same property on all messages you can use Enrich.WithProperty():

var logger = new LoggerConfiguration()
  .Enrich.WithProperty("ReportId", 10);
  .WriteTo.File(@"C:\Log.txt",
    outputTemplate: "{Timestamp:u} [{Level}] ({ReportId}) {Message}{NewLine}{Exception}")
  .CreateLogger()

Flat files are a great way to get up and running quickly with structured logs, but using a data store more suited to structured storage, e.g. CouchDB, RavenDB or Seq, will make it much nicer to view and correlate events based on property values.

其他提示

Log using below code :

Log.ForContext("CategoryName", "CategoryValue").Information("My Info");

Then you can query it using below query :

select EventType,@Properties.CategoryName AS CategoryName,  @Message, @Properties
from stream  
where CategoryName = 'CategoryValue'
limit 1000
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top