Robust logging is an essential tool in the dynamic field of application development for deciphering and resolving software behavior issues. This is an easy operation, made possible by the widely used.NET logging package Serilog. This post will discuss how to use Serilog to establish external logging sources for Windows Services and APIs, offering a complete logging solution.
Packages Required
Make sure you have installed the required Serilog packages before beginning implementation.
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
Serilog configuration in the API
You need to add the following settings to your appsettings.json file in order to configure Serilog in your API.
"LogBaseDirectory": "C:\\WindowsServiceLogs\\",
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "%APP_BASE_DIRECTORY%/Logs/log-.txt",
"rollingInterval": "Day"
}
}
]
}
The %APP_BASE_DIRECTORY% placeholder will be read from app settings and updated at the startup of the service.
In the startup of your API, configure Serilog as follows.
Now, let's create a simple worker class that utilizes Serilog for logging.
With Serilog, logging for APIs and Windows Services becomes an effortless endeavor. By configuring Serilog to use external logging sources, you ensure that your application's behavior is well-documented and can be easily analyzed. Embrace the power of Serilog to enhance your logging strategy and make troubleshooting a breeze.
0 comments:
Post a Comment