Use Serilog with Minimal API in .NET 6
November 19, 2021
- Categories
- Minimal API
- dotnet
- C#
- WebAPI
- ASP.NET
- Programming
If you want to replace the standard logging with Serilog in a Minimal API you have to do just a couple of steps.
At first, you have to add a reference to a NuGet package Serilog.AspNetCore. You can do it in Visual Studio or in the command line using dotnet CLI tool:
dotnet add package Serilog.AspNetCore
At second, you need to register Serilog as your logger in Program.cs:
var builder = WebApplication.CreateBuilder(args);
// remove default logging providers
builder.Logging.ClearProviders();
// Serilog configuration
var logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
// Register Serilog
builder.Logging.AddSerilog(logger);
var app = builder.Build();
// How to use logging inside your method
app.MapGet("/", (ILoggerFactory loggerFactory) => {
var logger = loggerFactory.CreateLogger("index");
logger.LogInformation("index called");
return "Hello world";
});
// How to use logging in Program.cs file
app.Logger.LogInformation("The application started");
app.Run();
That's it.
Recommended content
-
C# tutorial for beginners | 2 | Write your first C# program
March 06, 2021
-
C# tutorial for beginners | 1 | Setup development environment
February 17, 2021
-
Build a CI workflow in GitHub Actions with Buildah and Podman | Part 4 - How to live without Docker for developers
January 28, 2021
-
Push an image to Docker Hub and GitHub packages using Buildah | Part 3 - How to live without Docker for developers
January 17, 2021
-
How to live without Docker for developers - Part 2 | Native approach to build an image with Buildah
January 13, 2021
-
How to live without Docker for developers - Part 1 | Migration from Docker to Buildah and Podman
January 09, 2021
-
ASP.NET MVC 4 WebAPI. Support Areas in HttpControllerSelector
June 27, 2012