In this article, we will learn how to do structured logging using Serilog in asp.net core 7.0.
Logging is an essential part of an application. It helps us to track the application and even helps us to find the root cause of an error after the deployment of an application into production.
When we work with the asp.net core application, then we have an ILogger interface that helps us to do logging. But what if we want to have more control of the application? What if we want to have logging in a more structured way and with more detail? Then the Logging Frameworks or the Libraries come into the picture.
There are many ways through which we can do the logging, and every tool has cons and pros. Here we will discuss in detail Serilog, which helps us to log in a structured way. Serilog libraries are among the most popular for .NET Core Applications.
What is Serilog?
Serilog is the third-party logging library that overrides the default ILogger library and implements its own methods and logic in a structured way. It helps developers log events or messages into various applications like consoles, web, databases, etc.
Serilog supports structured logging, which enables more logging details and information about the event logged in the application. This logging helps us to find the root cause while debugging the code, or if we get the error in production, a fast fix to the end user.
To implement Serilog, we first need to create an asp.net core API application. So for that, let's open visual studio 2022 and click on create a new project and select an Asp.net core web application template.
Now give the project name 'SerilogApp' and click Next.
Now select the framework and click next
Once you click on next, it will create an application.
Now right-click on the application and go to the NuGet package manager.
In the NuGet package manager window, select the "Serilog.AspNetCore" and install it like below
If you don't want to install "Serilog.AspNetCore" from the NuGet package manager, then you can run the below command as well in the console package manager,
Install-Package Serilog.AspNetCore
Once the package is installed successfully, we must configure it in the program.cs class
we can call the UseSerilog function in the HostBuilder instance to configure Serilog using a lambda expression.
The simplest way to configure Serilog in the application is by calling ReadFrom.Configuration().
We can also use the UseSerilogRequestLogging() method to introduce the automatic HTTP request logging in the asp.net core API application.
using Serilog;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Structured Logging using Serilog in ASP.NET Core 7.0
Configuring Serilog With the appsettings.json
We need to add a new Serilog section block in the appsettings.json file.
Here we can configure below things:
Logging sinks to use with the Serilog
Override the default and the minimum log levels
Configure the file-logging arguments
Here we will add the Console and the File sinks to Serilog. And apart from it, we will also add some other configurations for the File sink in the Serilog.WriteTo configuration section. We can even configure the output path for all log files with the naming format.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Serilog": {
"Using": ["Serilog.Sinks.File", "Serilog.Sinks.Console"],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [{
"Name": "Console"
}, {
"Name": "File",
"Args": {
"path": "/logs/log-.txt",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter,Serilog.Formatting.Compact",
"rollingInterval": "Day"
}
}],
"Enrich": ["FromLogContext", "WithThreadId", "WithMachineName"]
}
}
Now go to Controller class and put any log you want to track. In my case, I kept below log information,
public WeatherForecastController(ILogger < WeatherForecastController > logger) {
_logger = logger;
_logger.LogInformation("WeatherForecast controller called ");
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable < WeatherForecast > Get() {
_logger.LogInformation("WeatherForecast get method Starting.");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
Now run your application and call the weatherForecast controller to get the method in swagger.
Once you hit the get method in swagger, you go to the file path ( this path we define in the appsettings.json -> write to -> file Path section), where we log it. In my case, it is in C: directory -> log folder -> log.txt
Now open this file you will see your log information is logged successfully in the file and console.
Since we have given in the appsettings.json file where we want to log the information, it is logging in 2 places.
Output is below
Serilog Structured Logging in JSON Format
Previously we added logs into a text file. Now if you want to log the information in JSON format, then we need to change the file format, and other things will automatically take care like below:
Now run your application again and call the weather forecast controller to get the method. Then go to the same directory path, a new JSON file you will see and you can find your logging information there as well.
In this article, we've seen the structured logging setup with the help of Serilog in ASP.NET Core 7.0. Logging into an application help developer while debugging an application, and Serilog helps us more with it.
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.