Logging using Serilog
Install Serilog
Serilog provides structured logging with sinks to write logs into various formats such as console, DataDog, DynaTrace, ElasticSearch, email etc.
In Rider, go to Tools > NuGet > Manage NuGet Packages for Dotnet.
Search for Serilog and install Serilog.AspNetCore 8.0.3.
Alternatively, in Terminal, usecd Library
dotnet add package Serilog.AspNetCore --version 8.0.3
If you're using a dark theme in Rider, logs might be written in black and impossible to read. Go to Settings > Editor > Color Scheme > Console Colors > Bright White and change Foreground to something like #FFFFF.
Configure Serilog
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
builder.Host.UseSerilog();
Log.Information("Starting Library {env}", builder.Environment.EnvironmentName);
builder.Services.AddControllers();
//...
Run the project. Open Run at bottom left or using Cmd + 4
Write logs using ILogger
Back in BookController, inject ILogger and write some logs using logger.LogInformation().
[ApiController]
[Route("[controller]")]
public class BookController(ILogger<BookController> logger) : Controller
{
[HttpGet]
public IActionResult Index()
{
logger.LogInformation("BookController.Index - Request");
var book = new { Id = 1, Title = "Dotnet" };
logger.LogInformation("BookController.Index - Response {@response}", book);
return Ok(book);
}
}
Run the project, call the API and view what is logged.
If you don't want the Microsoft logs, add .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) // add this
.WriteTo.Console()
.CreateLogger();