How to use Serilog in ASP.Net Core

Take advantage of Serilog to implement structured logging in your ASP.Net Core applications

How to use Serilog in ASP.Net Core
Nishan Joomun (CC0)

Logging is an essential feature for detecting and investigating issues in our applications. Logging frameworks make it easy to log event data to pre-configured log targets. However, if your log file contains unstructured data, it becomes a nightmare to query the data. This is where structured logging comes into play.

Structured logging makes it easy to query event data by ensuring that the data to be logged is written in a structured format. The format could be XML, JSON, or any other structured format that makes parsing the data easy. Structured logging also helps in processing the log files for log analytics.

Serilog is a third-party, open-source library for structured logging. It allows developers to easily log structured event data to the console, to files, and to all kinds of storage systems. This article presents a discussion of how we can work with Serilog in ASP.NET Core.

Create an ASP.NET Core project in Visual Studio

In this section we will create an ASP.NET Core application and use it to learn how we can work with Serilog. Follow the steps outlined below to create a new ASP.NET Core project in Visual Studio 2017.

  1. Launch the Visual Studio 2017 IDE.
  2. Click File > New > Project.
  3. Select the “ASP.NET Core Web Application” project template.
  4. Specify the name and location for your project.
  5. Click OK.
  6. In the “New ASP.NET Core Web Application” dialog window, select .NET Core.
  7. Select ASP.NET Core 2.1 as the version and “Web API” as the project template.
  8. Check the “Enable Docker Support” checkbox as we will be deploying our application using Docker.
  9. Ensure that the “No Authentication” option is selected. We won’t be using authentication here.
  10. Click OK.

This will create a new ASP.NET Core project in Visual Studio. Next we need to grab a few packages from NuGet. Select your project in the Solution Explorer window and right-click on “Manage NuGet Packages” to open the NuGet Package Manager window. Now install the following packages one by one.

  • Serilog. This package provides support for working with fully structured events.
  • AspNetCore. This package is used for providing Serilog support for ASP.NET Core applications.
  • Settings.Configuration. This package provides support for Microsoft.Extensions.Configuration so that you can read configuration data from appsettings.json. 
  • Sinks.Console. This is a Serilog sink that sends Serilog events to the console.
  • Sinks.RollingFile. This is a Serilog sink that provides support for storing log messages in a rolling file with fully structured events.

Use a Serilog sink to direct log data to a log target

Serilog takes advantage of sinks to send the logs to various logging targets such as a text file, a database, or even a log management solution. In other words, sinks are used to direct where the log messages should be sent.

If the Serilog packages have been successfully installed in your system, the following code snippet can be used to send log data to the console.

using (var logConfig = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger())
            {
                logConfig.Information("This is a test data.");
            };

Note that Serilog lets you choose from a variety of logging levels including verbose, debug, information, warning, error, and fatal messages.

Console logs are helpful for debugging purposes. When your application has been deployed in production, you might need to persist the logs to a file so that you can monitor the logs and perform log analysis. The Serilog.Sink.RollingFile package provides the support for working with rolling files. The following code snippet illustrates how you can configure a logger programmatically to log data to a file.

 var logger = new LoggerConfiguration()
             .MinimumLevel.Debug()
             .WriteTo.RollingFile(@"d:\log.txt", retainedFileCountLimit: 7)
             .CreateLogger();
            logger.Information("Hello World");

Register and configure Serilog in ASP.NET Core

To start leveraging Serilog in ASP.NET Core applications, you should register Serilog on the WebHostBuilder in the Program.cs file using the UseSerilog extension method as shown below.

WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog()
            .Build();

Next, add the following line in the Configure method to enable the Serilog middleware.

loggerFactory.AddSerilog();

Here’s how the Configure method in the Startup.cs file will look.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddSerilog();
            app.UseMvc();
        }

Finally, you should specify the necessary configuration in the appsettings.json file. Then you can leverage dependency injection to inject the logger instance and work with Serilog in your controller methods in much the same way you use any other middleware.

Because logging is an integral component of any application, the simplicity and flexibility of the logging framework is important. Serilog provides an easy-to-configure and easy-to-use logging component that can be used to log structured event data to various log targets using sinks.

Copyright © 2018 IDG Communications, Inc.