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.

Selecting the ASP.NET Core Web API project template in Visual Studio
Configuring the Web API project name and location in Visual Studio
Web API Additional information dialog with .NET 6.0, controllers and OpenAPI support enabled

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

Installing the Serilog NuGet packages

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.

ApplicationDbContext class with tblUsers and Employees DbSets
                    
 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

Serilog configuration and connection string in appsettings.json
                    
 "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);
    }
Employee repository interface with async CRUD methods

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

EmployeeService class calling stored procedures with Entity Framework Core
GetEmployeeListAsync and UpdateEmployeeAsync using FromSqlRaw and ExecuteSqlRawAsync

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

Registering Serilog, the DbContext and employee services in Program.cs

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

UpdateEmployee stored procedure in SQL Server
DeleteEmployeeByID and GetEmployeeByID stored procedures
AddNewEmployee stored procedure inserting into the Employees table
GetEmployeeList stored procedure selecting all employees

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

Employee API controller writing log messages with Serilog
AddEmployee (POST) and UpdateEmployee (PUT) actions in the Employee API controller
DeleteEmployee (DELETE) action in the Employee API controller

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.

Swagger UI for the Employee Web API
Swagger UI listing the Employee API endpoints
Swagger response from GET api/Employee/getemployeelist

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

Log entries written by Serilog to a text file in the logs folder