Integrating with WorkerService

Use Rollbar from within a WorkerService application

For the working sample, please look here.

Whenever you are trying to integrate Rollbar.NET SDK into an existing WorkerService application, the most optimal way is to do it via our Rollbar.NetPlatformExtensions module. It will also bring in the required dependency that is Rollbar core module/package. In this example, we also use optional Rollbar.AppSettings.Json module:

dotnet add package Rollbar.NetPlatformExtensions
dotnet add package Rollbar.AppSettings.Json

Then, configure the Rollbar Notifier within your WorkerService's appsettings.json file, for example:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "Rollbar": {
    "AccessToken": "17965fa5041749b6bf7095a190001ded",
    "Environment": "RollbarNetSamples",
    "Enabled": true,
    "MaxReportsPerMinute": 160,
    "ReportingQueueDepth": 120,
    "LogLevel": "Info",
    "ScrubFields": [
      "ThePassword",
      "TheSecret"
    ],
    "Person": {
      "UserName": "jbond",
      "id": "007"
    },
    "PersonDataCollectionPolicies": "Username, Email",
    "IpAddressCollectionPolicy": "CollectAnonymized"
  },

  "RollbarTelemetry": {
    "TelemetryEnabled": true,
    "TelemetryQueueDepth": 100,
    "TelemetryAutoCollectionTypes": "Network, Log, Error",
    "TelemetryAutoCollectionInterval": "00:00:00.3000000"
  }
  
}

Now, modify your Program.cs's CreateHostBuilder(...) methods by adding the RollbarLoggerProvider to its logging configuration, for example, like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using Rollbar;
using Rollbar.AppSettings.Json;
using Rollbar.NetPlatformExtensions;

namespace Sample.NetCore.WorkerService
{
  public class Program
  {
    public static void Main(string[] args)
    {
      CreateHostBuilder(args).Build().Run();
    }
    
    public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
      .ConfigureLogging((logging) => {
        
        // STEP.1 -  seed Rollbar infrastructure configuration:
        RollbarInfrastructureConfig rollbarInfrastructureConfig = 
          new RollbarInfrastructureConfig();
        
        // STEP.2 - reconfigure the seed from the appsettings.json file:
        if(!AppSettingsUtility.LoadAppSettings(rollbarInfrastructureConfig))
        {
          throw new ApplicationException("Couldn't load Rollbar configuration!");
        }
        
        // STEP.3 - init the Rollbar infrastructure with the loaded configuration:
        RollbarInfrastructure.Instance.Init(rollbarInfrastructureConfig);
        
        // STEP.4 - add a well-configured RollbarLoggerProvider:
        logging.ClearProviders();
        logging.AddProvider(
          new RollbarLoggerProvider(
            rollbarInfrastructureConfig.RollbarLoggerConfig
          ));
      })
      .ConfigureServices((hostContext,services) =>
      {
        services.AddHostedService<Worker>();
      });
    }
}

Recompile your application. From now on, anytime your codebase makes calls to an ILogger instance, the logged data will be forwarded to your Rollbar project dashboard, for example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Sample.NetCore.WorkerService
{
    public class Worker:BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(
          CancellationToken stoppingToken
        	)
        {
            while(!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation(
                  "Worker running at: {time}",
                  DateTimeOffset.Now
                  );
              
                await Task.Delay(1000,stoppingToken);
            }
        }
    }
}