This post is a contribution for C# Advent Calendar 2020. This is a simple guide for implementing Azure Application Insights using Serilog in a dotnet core worker service.
.Net Core worker services are best suited for long-running background tasks. These services can be run as a windows service or linux daemons. Worker services comes with DI, logging and configuration features out-of the box.
First create a new Worker Service project via your favorite terminal using the following simple command
dotnet new worker -o WorkerService
Install the following Serilog Packages in your project directory.
- Serilog
- Serilog.Extensions.Hosting
- Serilog.Settings.Configuration
- Serilog.Sinks.Console
- Serilog.Sinks.ApplicationInsights
dotnet add package Serilog
dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Settings.Configuration
Copy your Application Insights Instrumentation Key from Azure Portal and update your appsettings.json with the following json
{
"Serilog": {
"MinimumLevel": "Debug",
"WriteTo": [
"Console",
{
"Name": "ApplicationInsights",
"Args": {
"instrumentationKey": "__ApplicationInsightsInstrumentationKey__",
"restrictedToMinimumLevel": "Information",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
]
}
}
In Program.cs file import Serilog namespace
using Serilog;
and update your CreateHostBuilder to instansiate Serilog logger and chain with UseSerilog() method to replace the default logging provider with Serilog.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(hostContext.Configuration)
.CreateLogger();
}).UseSerilog();
Use the following command in your project directory to run the worker service.
dotnet run
You should start seeing your console messages in your Azure portal Application Insights logs
Top comments (0)