January 01, 2024 by Anuraj
AspNetCore Logging Serilog
Serilog stands out as an excellent third-party library for implementing structured logging in ASP.NET Core applications. The adoption of structured logging is crucial for generating logs that are both easily readable and filterable. Opting for SQL Server as a log destination provides the advantage of harnessing SQL querying capabilities for efficient log filtering. This becomes particularly beneficial when our application is already integrated with SQL Server.
Now, let’s explore the steps involved in implementing Serilog SQL logging in ASP.NET Core.
First we need to add the Serilog related NuGet packages to the ASP.NET Core application.
I am using a .NET 8 Web API project for this demo. We can create the web api application using
dotnet new webapi command.
Next in the
Program.cs class add the following code. For demo purposes, I am creating the log table and database in runtime. I will include the script to create the log table, if EF Core migrations are used to create the Sql database / tables.
Now we can modify the application and add following logging code.
Here is the screenshot of the table -
And here is the Sql Table schema.
We can execute this Sql script and set the
Currently I am configuring everything from the code. We can also configure the values in
appsettings.json and use it. Here is the
And we can modify the code like this.
This way we can configure Serilog in ASP.NET Core with log destination as Sql Server. We explored how to configure Serilog with Sql Server in ASP.NET Core Web API. Manually creating the Sql table with the schema. Also how to configure the logging with Sql Server.
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub