How to track logging information using Serilog in Web API ?

In this tutorial I am going to implement basic logging mechnism to log the exception information in Web API using Serilog a third party library that is used to store the generated logs in a text file or database based on the user's choice. Previously we have build applications using the Entity Framework code first approach and implemented Serilog for logging purpose, here is step by step implementation provided

Steps to be followed here are :-

  • Create a WEB API Project.
  • Install Serilog package from Nuget package manager.
  • Setting up the Serilog Configuration and connection string into the AppSettings.Json file.
  • Register the Serilog Middileware in program.cs file
  • In AppSettings.Json file you have to provide the file path where you want to store the log information.
  • Create a Constructor of Controller and initialize the ILogger object into it and use it to store the logs information over the controller level.

Note :- In this implementation I have used Basic Crud operations using the Stored Procedure in SQL Server and access it in application by Entity Framework , you can avoid the Stored Procedure and can implement CRUD by your own ways of coding standards.

To start with create a Web API project using the web api template as shown in below image and name the project then select for some default options for minimal api's and target framework as like in below images.

Image is not available
Image is not available
Image is not available

Install Serilog package from nuget package manager as shown in below image.

Image is not available

Now add Employee Model class and add the below properties into it.

                    
 [Key]
 public int EmployeeId { get; set; }
 public string EmployeeName { get; set; }
 public string EmployeeDescription { get; set; }
 public int EmployeeSalary { get; set; }
public int YearOfService { get; set; }

Now add DBContext class and add the below code into it.

Image is not available
                    
 public class ApplicationDbContext:DbContext
 {     
      public ApplicationDbContext(DbContextOptions
                     options) 
      : base(options)
      {

      }
      public DbSettblUsers{get;set;}
      public DbSet Employees {get;set;}
}

Now add the Serilog Configuration and Connection string into the AppSettings.json file

Image is not available
                    
 "ConnectionStrings": {
    "DBCS": "server=DESKTOP-1CO7VJ1\\SQLEXPRESS;
    database=FirstCrudDB;Trusted_Connection=true;
    encrypt=false;"
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log.txt",
          "rollingInterval": "Day"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "FirstCruWebAPI"
    }
  }

Now add a repository folder in the project and create an Interface named it IEmployeeRepo and write the below methods inside it.

                    
public interface IEmployeeRepo
    {
        public Task> GetEmployeeListAsync();
        public Task> GetEmployeeByIdAsync(int Id);
        public Task AddEmployeeAsync(Employee Employee);
        public Task UpdateEmployeeAsync(Employee Employee);
        public Task DeleteEmployeeAsync(int Id);
    }
Image is not available

Now add a Service folder in the project and create an EmployeeService class into it and write the below code inside it.

Image is not available
Image is not available

Now add highlighted code into the program.cs file for accessing the DB Connection and register the serilog and employee services into it.

Image is not available

Now Create Stored procedures into the SQl database like below images.

Image is not available
Image is not available
Image is not available
Image is not available

Now create an API controller and named it Employee and write the code as shown in below images.

Image is not available
Image is not available
Image is not available

Now run the application you will get an swagger UI as shown in below images and hit any API Url you will also get an text file in solution explorer in logs folder.

Image is not available
Image is not available
Image is not available

After hitting the API Url from swagger you can get some log information in text file as shown in below image.

Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.