How to use Serilog ForContext

Marco picture Marco · May 13, 2014 · Viewed 21.2k times · Source

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"); 

Answer

Nicholas Blumhardt picture Nicholas Blumhardt · May 18, 2014

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.