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().Create.Logger();
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

Clone this wiki locally