Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Integrate Serilog (Logging Framework) with ASP.NET Core

0.00/5 (No votes)
3 Dec 2016 1  
Integrate serilog with asp.net core application.

Introduction

Serilog

This is a very good logging framework for .NET. It is very easy to integrate in ASP.NET Core. It is an open source framework. If you want to customize it for your project needs, it is very easy.

Serilog Sinks

It helps to log events in different storages, e.g. SQL Server, Elastic Search, Email, MongoDb.

Source URL of serilog sinks is https://github.com/serilog/serilog/wiki/Provided-Sink.

How Serilog Works ?

Logging Flow

I think the diagram is self explanatory.

Configure Serilog

  1. Create a new application in ASP.NET Core.
  2. Install the following packages of Serilog:
    • "Serilog": "2.4.0-dev-00766"
    • "Serilog.Sinks.MSSqlServer": "4.2.0"
    • "Serilog.Extensions.Logging": "1.4.0-dev-10136"

Startup.cs

public IConfigurationRoot configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
   // Add framework services.
   services.AddMvc();
   
   var columnOptions = new ColumnOptions
   {
       AdditionalDataColumns = new Collection<DataColumn>
       {
            new DataColumn {DataType = typeof (string), ColumnName = "User"},
            new DataColumn {DataType = typeof (string), ColumnName = "Other"},
       }
   };

   columnOptions.Store.Add(StandardColumn.LogEvent);

   services.AddSingleton<Serilog.ILogger>
            (x => new LoggerConfiguration()
                  .MinimumLevel.Information()
                  .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                  .MinimumLevel.Override("System", LogEventLevel.Error)
                  .WriteTo.MSSqlServer(configuration["Serilog:ConnectionString"]
                  ,configuration["Serilog:TableName"] 
                  ,LogEventLevel.Information, columnOptions: columnOptions)
                  .CreateLogger());
}

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

appsettings.json

"Serilog": {
   "ConnectionString": "Server=(localdb)\\ProjectsV13;Database=TestDatabase;trusted_connection=true",
   "TableName": "Logs"
 }

Controller

[Route("api/[controller]")]
    public class CustomerController : Controller
    {
        private readonly ICustomerService _customerService;
        private readonly Serilog.ILogger _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="customerService"></param>
        /// <param name="logger"></param>
        public CustomerController(ICustomerService customerService, Serilog.ILogger logger)
        {
            _customerService = customerService;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            object one = 123;
            object two = 123;

            _logger.ForContext("User","Aditya").Information("Data Added Successfully");
            _logger.Error("Data Critical Added Successfully");
            _logger.Fatal("Data Error Added Successfully");

            var result = _customerService.GetCustomers();
            return Ok(result);
        }
     }

Table Script

CREATE TABLE [dbo].[Logs] (
    [Id]              INT            IDENTITY (1, 1) NOT NULL,
    [Message]         NVARCHAR (MAX) NULL,
    [MessageTemplate] NVARCHAR (MAX) NULL,
    [Level]           NVARCHAR (128) NULL,
    [TimeStamp]       DATETIME       NOT NULL,
    [Exception]       NVARCHAR (MAX) NULL,
    [Properties]      XML            NULL,
    [User]            NVARCHAR (50)  NULL,
    [Other]           NVARCHAR (50)  NULL,
    [LogEvent]        NVARCHAR (MAX) NULL
);

How to Create Custom Columns in Database?

var columnOptions = new ColumnOptions
                    {
                        AdditionalDataColumns = new Collection<DataColumn>
                        {
                           new DataColumn {DataType = typeof (string), ColumnName = "User"},
                           new DataColumn {DataType = typeof (string), ColumnName = "Other"},        
                        }    
                    }

We can use this piece of code to integrate custom columns with sqlserver sink.

How to Store Data in Custom Columns?

To store data in custom columns, we have to use enrichers.

e.g. _logger.ForContext("User","Aditya").Information("Data Added Successfully");

User is a custom column in database.

How to Avoid Logging of Microsoft and System Information?

When you implement serilog in ASP.NET Core, it will automatically log ASP.NET pipeline information in the database. To avoid logging of Microsoft and system information, we need to setup the logger configuration.

Levels of log are:

  1. Verbose
  2. Debug
  3. Information
  4. Warning
  5. Error
  6. Fatal

Logger Configuration

  • .MinimumLevel.Information() // It means log all events which are of type information or above.
  • .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // It implies log all Microsoft events which are of type warning or above.
  • .MinimumLevel.Override("System", LogEventLevel.Error) // It implies log all system events which are of type error or above.

Points of Interest

Serilog is very easy to integrate with ASP.NET Core. It provides you flexibility to store events in different storages with an ease. With a very few configuration settings, you can integrate multiple sinks.

I have created a sample application and it is uploaded in github at https://github.com/Head-Strong/AspNetCore.Sample.Application.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here