SeriLog & Application Diagnostic Logging

Show me an application that doesn't log anything and i'll show you an application which is hard to debug.

Every application we write should have a healthy sprinkling of diagnostic logging embedded throughout its logic. A trace to show us what's happening on the inside from the outside. In the past, I've hand-rolled my own bespoke logging classes to output either to file, database or simply console.

Not any more!

The problem has been solved. It's been done. There are libraries out there like Log4Net or Nlog

But from now on, I intend to standardise all my C# code to use SeriLog.

SeriLog is an example of a library where so many developers have poured in so much time that any home grown library cannot compete.

Why waste your time? Just "nuget" it into your project and be done. Move on.

Why is it so cool?

Because it's simple. And because it supports many, many outputs. They call them sinks and there is a sink for everything as you can see in the image above.

But the real cool part is that you can pass a data model to SeriLog and it will serialise the properties in JSON format.

Want to see some sample code? The github pages have plenty of samples there but the code sample below demonstrates how SeriLog logs to:

  • The screen
  • A rolling log file on disk
  • And a database table
using Serilog;

namespace OceanAirdrop
{
class SomeModel
{
public int UserId { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
}

public class SeriLogger
{
public static void Main(string[] args)
{
string connName = "db-connection-string";

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("AppLogs\\SomeCoolApp-{Date}.txt")
.WriteTo.MSSqlServer(connName, "some_cool_app_log")
.CreateLogger();

try
{
Log.Information("Some important log information!");

var someData = new User { UserId = 256, Name = "Ocean Airdrop", BirthDate = DateTime.Now };

Log.Information("Some more logging: {@User}", someData);
}
catch (Exception ex)
{
Log.Error(ex, "Something went kaboomski!");
}
}
}
}

Comments

Popular posts from this blog

OxyPlot Charting Control

Android, Self-Signed Certificates and OkHttp