Serilog is a popular logging library for .NET applications. It provides structured logging, which allows logs to be written in a format that is easy to read, search, and analyze.
Follow these steps to integrate Serilog into your ASP.NET Core application:
Install the necessary Serilog packages using the .NET CLI or NuGet Package Manager.
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
These packages include the core library and sinks for writing logs to the console and a file.
Set up Serilog in your Program.cs
file.
// Program.cs
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Host.UseSerilog();
var app = builder.Build();
app.MapGet("/", () => "Hello, Serilog!");
app.Run();
This configuration reads settings from the app configuration and writes logs to the console and a rolling log file.
appsettings.json
Add Serilog settings in the appsettings.json
file for centralized configuration.
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{ "Name": "File", "Args": { "path": "logs/log-.txt", "rollingInterval": "Day" } }
]
}
}
This configuration sets the logging level and defines sinks for the console and file.
Inject ILogger<T>
to log messages in your application.
// Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
public class HomeController : ControllerBase
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpGet("/")]
public IActionResult Index()
{
_logger.LogInformation("Hello from Serilog!");
return Ok("Check the logs for the message.");
}
}
Use _logger
to log messages with different severity levels, such as Information, Warning, and Error.