Click here to Skip to main content
15,886,026 members
Articles / Web Development / ASP.NET / ASP.NETvNext
Tip/Trick

Integrate Serilog (Logging Framework) with ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
3 Dec 2016CPOL2 min read 32.4K   2   7
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

C#
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

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

Controller

C#
[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

SQL
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?

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionSerilog is not logging into DB Pin
Member 1193328829-Jul-17 2:15
Member 1193328829-Jul-17 2:15 
GeneralRe: Serilog is not logging into DB Pin
Adi_Mag10-Aug-17 9:30
Adi_Mag10-Aug-17 9:30 
GeneralRe: Serilog is not logging into DB Pin
Member 1193328810-Aug-17 19:26
Member 1193328810-Aug-17 19:26 
QuestionPackage Serilog.Sinks.MSSqlServer 4.2.0 is not compatible with netcoreapp1.0 Pin
Ashwadh4-Jan-17 0:11
Ashwadh4-Jan-17 0:11 
AnswerRe: Package Serilog.Sinks.MSSqlServer 4.2.0 is not compatible with netcoreapp1.0 Pin
Adi_Mag8-Jan-17 7:05
Adi_Mag8-Jan-17 7:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.