Serilog is an open-source logging library for .NET applications. It provides a flexible and highly extensible way to capture and store log information, making it easier to monitor and troubleshoot applications.
Serilog is known for its structured logging capabilities and can be used in various .NET platforms, including ASP.NET Core, ASP.NET Web API, and other .NET applications.
This example will help you set up a basic Web API application using Serilog for logging.
Step 1: Create a New ASP.NET Web API Project
- Create a new ASP.NET Core WebApi Project.
- Name your project and click “Create.
Step 2: Install Serilog Packages
Open the NuGet Package Manager Console and install the following packages:
- Serilog
- Serilog.AspNetCore
Step 3: Configure Serilog in Program
.cs
In the Program.cs file, use the following code to configure Serilog and integrate it with the ASP.NET Core logging framework:
builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));
This code sets up Serilog to log to the application and seamlessly integrates it into the ASP.NET Core logging system.
Step 4: Configure Serilog in appsetting.json
This file store the Serilog configuration settings. This JSON configuration specifies that Serilog should use the console sink, log at the “Information” level, and enrich log entries from the log context.
{
"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": "C:/Seri/serilog-.txt",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter,Serilog.Formatting.Compact",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithThreadId", "WithMachineName" ]
}
}
Step 5: Create a Controller
In this example I added the logging information and store that logging statement in file which i have created in my C drive and specified in appsettings.json.
using Microsoft.AspNetCore.Mvc;
namespace Seriapps.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
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 = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
In the constructor, I use the logger to log an information message indicating that the controller has been called.
_logger.LogInformation("WeatherForecast get method Starting.");
This line logs an information message when the Get
method is starting. The log level is set to “Information,” which is a standard logging level indicating general information about the application’s state.
Step 6: Run the Program
Build and run your ASP.NET Web API project. When the application runs, it logs information to both the console and a specified .txt file, as configured in appsettings.json.
In console,
In .txt file,
Key features and concepts of Serilog include:
- Structured Logging: Serilog excels in structured logging, allowing developers to log information in a structured format, often using JSON or key-value pairs. This structured data makes it easier to search, filter, and analyze log entries.
- Extensibility: Serilog is highly extensible and can be easily integrated with various sinks (output destinations) such as console, files, databases, cloud-based services, and more. Additionally, you can create custom sinks to log to specific destinations.
- Filtering: Serilog provides a flexible filtering mechanism that allows you to control which log events are captured and sent to the output sinks based on criteria like log level, message content, or context.
- Enrichment: You can enrich log events with additional context information, such as user IDs, request information, or any custom properties. This is helpful for debugging and auditing.
- Log Levels: Serilog supports different log levels, including Debug, Information, Warning, Error, and Fatal, allowing you to categorize log events by their severity.
- Configuration: Serilog can be configured programmatically or through configuration files, like
appsettings.json
, making it easy to adapt to various environments and scenarios. - Asynchronous Logging: Serilog supports asynchronous logging, which can help improve the performance of your application by offloading the logging work to background threads.
- Integration with .NET Ecosystem: Serilog integrates seamlessly with various parts of the .NET ecosystem, including ASP.NET Core, Entity Framework Core, and other popular libraries.
In this blog, we covered the use of Serilog for logging within an ASP.NET Core Web API application. Logging is a crucial aspect of application development, as it allows you to record and monitor events and behaviors in your application, making it easier to diagnose issues and understand how your application is functioning.
No Comment! Be the first one.