In my previous post, we had discussed the various logging providers for ASP.NET Core. Serilog is the one of the logging provider that support dinamic logging. Here in this post, we will discuse who to use Serilog in ASP.NET Core Web App and ASP.NET Core Web API.
ASP.Net Core Logging using Serilog
Getting StartedSerilog is a diagnostic logging library for .NET applications where logs can be written in file or in console or elsewhere. It is easy to set up and has a clean API. It has support for structured logging shines when instrumenting complex, distributed, and asynchronous applications and systems more is portable between recent .NET platforms.
Serilog can be used in web app and web api of ASP.NET CORE. Here we are not going to discuss to develop web app or api projects. you can use the instructions or steps given below in your existing website development project.
Follow the below instructions to integrate Serilog libraries in your project.
Step-1: Install Serilog supportive libraries
Install the following libraries from NuGet using NuGet Package Manager.
- Serilog
- Serilog.AspNetCore
- Serilog.Sinks.File
Step-2: Configure Serilog
Find the appsetting.json in your project and add below configuration in the appsetting.json file.
"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-.log",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true
}
}
]
},
Step-3: Inject the Seriallog
After installing libraries and setting up the log level in the appsetting.json file Serial log need to be injected as service. the following code describes how to inject it.
builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));
app.UseSerilogRequestLogging();
Step-4: Use Seriallog in classes
After completing above settings, you can now use the Seriallog in your project classes like below code example
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Get Weather forecast called sucessfully");
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();
}
Thanks
nice description
ReplyDelete