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

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
var _colors = new List<string> { "red", "blue", "green" };
Log.Information("Basic Colors - {Colors}", _colors)
// Output: Basic Colors - ["red", "blue", "green"]

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

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"

Clone this wiki locally