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.
Install the Serilog package from the NuGet Package Manager, as shown in the image below.
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.
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.
"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);
}
Now add a Service folder to the project, create an EmployeeService class in it and write the code below.
Now add the highlighted code to the Program.cs file to configure the database connection and register Serilog and the employee services.
Now create the stored procedures in the SQL database, as shown in the images below.
Now create an API controller named Employee and write the code, as shown in the images below.
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.
After calling the API from Swagger, you can see the log information in the text file, as shown in the image below.