DEV Community

Cover image for Application Insights for Worker Service using Serilog
Ram Hemasri
Ram Hemasri

Posted on

Application Insights for Worker Service using Serilog

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
Enter fullscreen mode Exit fullscreen mode

Install the following Serilog Packages in your project directory.

  1. Serilog
  2. Serilog.Extensions.Hosting
  3. Serilog.Settings.Configuration
  4. Serilog.Sinks.Console
  5. 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
Enter fullscreen mode Exit fullscreen mode

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"
        }
      }
    ]
  }
}

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Use the following command in your project directory to run the worker service.

dotnet run
Enter fullscreen mode Exit fullscreen mode

You should start seeing your console messages in your Azure portal Application Insights logs

Console messages log

Application Insights Log

Top comments (0)