Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Serilog ForContext

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"); 
like image 381
Marco Avatar asked May 13 '14 17:05

Marco


Video Answer


2 Answers

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.

like image 75
Nicholas Blumhardt Avatar answered Sep 30 '22 11:09

Nicholas Blumhardt


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
like image 27
Prasad Shetty Avatar answered Sep 30 '22 11:09

Prasad Shetty