문제

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