.NET 7 - Minimal APIs with Serilog
.NET 7 - Minimal APIs with Serilog

.NET 7 – Minimal APIs with Serilog Logging Providers

I have been writing about minimal APIs since past few articles. In previous article, we have used EF Core code first approach to setup the data access layer with minimal API project.

In this article, we are going to configure logging in that same project.

Default Logger

In our MinimalApiDemo project, there is a class AppBuilder, which builds and returns WebApplication instance. The WebApplication instance has a property Logger, which provides the logging provider. The logging provider has various methods to log the data.

Just for the sake of trying, let’s try to add some log statements in the Main method, and then try to run the program. We can see that those log statements have been logged on the console.

This means, that by default, the console logging provider is configured in our project.

.NET 7 – Minimal Api Demo – Default Logger

Which logging provider we want to use ?

Now, let’s say we want to configure some other logging provider. There are many different types of logging providers available in .NET. Also there are also some third-party providers too. So the obvious question now is – which logging provider do we want to use ?

For the sake of demo, let’s try to use Serilog. Serilog is a famous library (set of NPM Packages) which provide APIs for diagnostic logging. The logging output can be sent to Console, Files, ApplicationInsights or almost any other well-known diagnostic logging store.

Configuration Application For Logging

So now, it is time to perform some action. Let’s add references to the NuGet packages.

Once the NuGet packages are added to the API project, we can start modifying the code. Let’s go to AppBuilder and then add some code to clear the existing log providers. Then add the code to use Serilog sinks.

The modified code is shown below. Here the configuration would tell application to send diagnostic logs to a file named serilog-file.txt and also to the console.

Run and Verify

Now, if we run the application, we can see that console shows the logs sent by Serilog.

.NET 7 – Console Logs in Minimal Api Demo Project with Serilog Logger

Also, after stopping the application, we can open the file and see the logs there too.

.NET 7 – Serilog file sink demo with Minimal APIs

So, we have successfully configured our minimal API demo project to use Serilog diagnostics logging package.

I hope you find this information helpful. Let me know your thoughts.

Leave a ReplyCancel reply