Skip to content

How to Log Information Using Serilog in Web API

In this tutorial, I implement a basic logging mechanism to log exception information in a Web API using Serilog, a third-party library that stores the generated logs in a text file or a database, depending on your choice. We build the application using the Entity Framework code-first approach and add Serilog for logging. Here is the step-by-step implementation.

Steps to follow:

  • Create a Web API project.
  • Install the Serilog package from the NuGet Package Manager.
  • Set up the Serilog configuration and the connection string in the appsettings.json file.
  • Register Serilog in the Program.cs file.
  • In the appsettings.json file, provide the path of the file where you want to store the log information.
  • Inject the ILogger object through the controller's constructor and use it to write log information at the controller level.

Note: This implementation uses basic CRUD operations with stored procedures in SQL Server, called through Entity Framework. You can skip the stored procedures and implement CRUD in your own way.

To start, create a Web API project using the Web API template, as shown in the image below. Name the project, then select the default options and the target framework, as shown in the images below.

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 the Serilog package from the NuGet Package Manager, as shown in the image below.

Installing the Serilog NuGet packages

Now add an Employee model class with the properties below.

 [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 a DbContext class with the code below.

ApplicationDbContext class with tblUsers and Employees DbSets
 public class ApplicationDbContext:DbContext
 {     
      public ApplicationDbContext(DbContextOptions
                    <ApplicationDbContext> options) 
      : base(options)
      {

      }
      public DbSet<UserRegistration>tblUsers{get;set;}
      public DbSet<Employee> Employees {get;set;}
}

Now add the Serilog configuration and the connection string to 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 to the project, create an interface named IEmployeeRepo and write the methods below in it.

public interface IEmployeeRepo
    {
        public Task<List<Employee>> GetEmployeeListAsync();
        public Task<IEnumerable<Employee>> GetEmployeeByIdAsync(int Id);
        public Task<int> AddEmployeeAsync(Employee Employee);
        public Task<int> UpdateEmployeeAsync(Employee Employee);
        public Task<int> DeleteEmployeeAsync(int Id);
    }
Employee repository interface with async CRUD methods

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

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

Now add the highlighted code to the Program.cs file to configure the database connection and register Serilog and the employee services.

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

Now create the stored procedures in the SQL database, as shown in the images below.

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 named Employee and write the code, as shown in the images below.

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 get the Swagger UI, as shown in the images below. Call any API URL, and a text file appears in the logs folder in Solution Explorer.

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

After calling the API from Swagger, you can see the log information in the text file, as shown in the image below.

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