Structured Logging with AspNet Core using Serilog and Seq

In this episode we take a first look at structured logging from an AspNet Core application using Serilog and Seq.

Screencast

Adding Serilog

Configuring the web app to leverage serilog only requires 3 simple steps. First make sure to get the nuget packages by adding these lines to your packages.json.

    "Serilog.Extensions.Logging": "1.0.0-rc2-*",
    "Serilog.Sinks.RollingFile": "2.0.0-rc-*",
    "Serilog.Sinks.Seq": "2.0.0-rc-*"

In the constructor of your Startup.cs file, configure the logger to log to both the Seq endpoint and to a rolling file, or that’s at least what I did.

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel
        .Information()
        .WriteTo.RollingFile("log-{Date}.txt", LogEventLevel.Information)
        .WriteTo.Seq("http://localhost:5341/")
        .CreateLogger();

This assumes that you’ve installed the Seq MSI on your local machine, you can grab it from here. Finally, add serilog to the logger factory in the configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddSerilog();
}

That’s it, browse http://localhost:5341 and you should see the following:
seq

Structured Logging

To log entire objects that will be queryable, simple pass an @-sign in front of the tag name that you want to create. For instance, to log a person object and create a tag accordingly from the HomeController we do the following.

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

public class HomeController : Controller
{
    private readonly ILogger _logger;

    public HomeController(ILogger logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        var p = new Person { Firstname = "Ajden", Lastname = "Towfeek" };
        _logger.LogInformation("Just trying out the logger {@Person}", p);
        return View();
    }
}

Which will result in the following queryable log post in Seq:
seq_logpost

Conclusions

It’s really powerful to log information with rich, structured and queryable log data but there are also some downsides for the moment with using Seq that I’d like to point out.

  • Shipping logs over http/https adds extra overhead.
  • Seq Service needs to be installed on separate virtual machine than your Azure Web App (assuming you’re using Azure). Meaning you’ll need to pay for an extra VM just for logging.
  • Free license is only usable for development, can’t have open endpoints that anyone can log to in production.

Having that said, I still think the idea of structured logging is very interesting and it provides an extra dimension of information when fixing/reproducing bugs. I just won’t be using Seq in production just yet.

Until next time, have an excellent day!