Skip to content

SeriLog

Kota edited this page Sep 24, 2018 · 13 revisions
  • Serilog provides diagnostic logging to files, the console, and elsewhere

Installation - Nuget

  • SeriLog: Basic configurations of SeriLog

  • Sinks: Which helps in storing the logs into specific type of storage systems

    • Serilog.Sinks.Console
    • Serilog.Sinks.ColoredConsole
    • Serilog.Sinks.File
    • Serilog.Sinks.RollingFile
  • Basic Settings

var template = "{Timestamp:yyyy-MMM-dd HH:mm::ss} [{Level}] {Message}{NewLine}{Exception}";
var _logger = new LoggerConfiguration()
                            .WriteTo.Console()
                            .WriteTo.ColoredConsole(Serilog.Events.LogEventLevel.Verbose, outputTemplate: template)
                            .WriteTo.File("log.txt")
                            .WriteTo.RollingFile("rollinglogfile.txt", retainedFileCountLimit: 2)
                            .CreateLogger();
Log.Logger = _logger;
Log.Logger.Information("Log Message");

Logging Structured Data

  • Scalar Data: Boolean, Int (byte <=> decimal), String, DateTime, Others (GUID, URI, nullables)

  • Collections, Objects, Dictionary<key, value> (key must be Scalar),

  • Simple Scalar values

//      String, Int, DateTime, GUID
Log.Information("Added user {UserName}, Age {UserAge}, DOB {BirthDate} - ID {_id}", 
                                                  _name, _age, _birthDate, GUID.NewGUID);
// output: Added user "Kota", Age 99, DOB 05/20/2018 01:01:01 - 616165sda1sd-asfjwqafaw-sfa
  • Collections and Objects
//      LIST
var _colors = new List<string> { "red", "blue", "green" };
Log.Information("Basic Colors - {Colors}", _colors)
// Output: Basic Colors - ["red", "blue", "green"]

//      DICTIONARY
var _countryCodes = new Dictionary<string, int> { {"India",91 }, {"UK",44 } };
Log.Information("Country Codes - {CountryCodes}", _countryCodes)
// Output: Country Codes - [ ("India": 91 ), ("UK": 44) ]

//      OBJECT
class Color { 
  public string Red {get; set;}
  public string Green {get; set;}
  public string Blue{get; set;}

  public override string ToString()
  {
    return string.Format("R:{0} G:{1} B:{2}", Red, Green, Blue)
  }
}
var headerColor = new Color{ Red=100, Green=0, Blue=50 };
Log.Information("Header Color - {HeaderColor}", headerColor)
//Output: Header Color - namespace.Color -> It calls ToString() of Color object. So overwrite ToString() of Color class

//output: Header Color - "R:100 G:0 B:50"
// this stores the data in the form of string and not objects
  • Destructured Objects (@ - Destructuring operator)
// from the example above - now serilog saves the whole object (not string)
Log.Information("Header Color - {@HeaderColor}", headerColor)
//output: Header Color - Color { Red:100, Green:0, Blue:50 }

// To log only few properties and not all - change Config
Log.Logger = new LoggerConfiguration()
                  .Destructure.ByTransforming<Color>(x=> new {x.Red, x.Green})
                  .WriteTo.Console().CreateLogger();
Log.Information("Header Color - {@HeaderColor}", headerColor)
//output: Header Color - Color { Red:100, Green:0 }

Sinks

  • Are place where we can store messages. Ex: Azure Table Storage, Colored/Console, Rolling/File, Elastic Search, ElmahIO, Log4Net, MongoDb, MS SQL Server, Seq, RavenDB, Trace, Win Events etc..

Serliog.Sinks.RavenDB example

// add RavenDB Sink
var logDocumentStore = new DocumentStore{ Url="http://localhost:8080", Defaultdatabase = "log" }
logDocumentStore.Initialize();
var _logger = new LoggerConfiguration()
                            .WriteTo.RavenDB(logDocumentStore)
                            .CreateLogger();
Log.Logger = _logger;

userToAdd = new User { name ="sda", Age = 21 }
Log.Information("Added user {@NewUser}", userToAdd);
// output: http://localhost:8080/raven/studio.html

Beyond Fundamentals

  • Formatting
//      STRING
Log.Information("Added {username}, name")
// Added "Kota"
Log.Information("Added {username:l}, name")
// Added Kota

//      NUMBER
Log.Information("PI is {pi}, Math.PI")
// PI is 3.14159265358979
Log.Information("PI is {pi:0.00}, Math.PI")
// PI is 3.14 ==> storage will still have all decimals
  • Levels (verbose, Debug, Information, Warning, Error, Fatal)
    • Configuring minimum level (default Information)
    Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .WriteTo.Console().CreateLogger();
    
    • Sink Specific
    Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
                    .WriteTo.File("verboselog.txt", restrictedToMinimumLevel: LogEventLevel.Verbose)
                    .CreateLogger();
    
    
    • Adding Logging Context
    var contextLogger =   Log.Logger.ForContext<Program>();
    contextLogger.Information();
    
    // output: "SourceContext": "namespace.Program"
    
     Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.Console()
                    .Filter.ByExcluding(x => x.properties.ContainsKey("CommandLineArguements"))
                    .CreateLogger();
    
    Log.Information("Params {CommandLineArguements}", args); // will not be logged
    
    // some more
    .Filter.ByExcluding(Matching.WithProperty("CommandLineArguements")) // same as above
    .Filter.ByIncludingOnly(x => x.MessageTemplate.Text.Contains("Attempting to divide"))
    .Filter.ByExcluding(Matching.FromSource<Program>())
    .Filter.ByExcluding(Matching.FromSource("ConsoleApplication"))
    
    • Correlating Log Entries
      • Adding property for all log entries
      Log.Logger = new LoggerConfiguration()
                    .Enrich.WithProperty("ApplicationName", "SampleApp")
                    .WriteTo.Console()
                    .CreateLogger();
      
      • Adding
      class ApplicationDetailsEnricher
      {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
          logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty())
        }
      }
      
      Log.Logger = new LoggerConfiguration()
                    .Enrich.With(new ApplicationDetailsEnricher)
                    .WriteTo.Console()
                    .CreateLogger();
      
    
    
    
    
    
    
    
    
    
    
    
    
    
    

Clone this wiki locally