2

I integrated Sentry with .NET Core 6.0 Worker Service this way:

NuGet: Sentry 3.17.1

// Program.cs:

using Sentry;

var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
using (SentrySdk.Init(o =>
{
    o.Dsn = sentryDsn;
    o.Debug = true;
    o.TracesSampleRate = 1.0;
}))
{
    IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();

    await host.RunAsync();
}
// Worker.cs:

namespace demo_heroku_sentry_worker;
using Sentry;

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);

            try
            {
                throw new ApplicationException("Exception inside of worker service");
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
            }

            await Task.Delay(10000, stoppingToken);
        }
    }
}

This is working in some way because I see the manually captured error on my Sentry Dashboard. However I'm concerned about these warning messages I receive on the Application Output:

      Worker running at: 05/11/2022 15:51:06 +02:00
  Debug: Failed to report an error on a session because there is none active.
   Info: Capturing event.
  Debug: Running processor on exception: Exception inside of worker service
  Debug: Creating SentryStackTrace. isCurrentStackTrace: False.
  Debug: Running main event processor on: Event abb5b3e2ee3a4dbd***********
   Info: Envelope queued up: 'abb5b3e2ee3a4dbda50ef***********'
  Debug: Envelope abb5b3e2ee3a4dbda50e*********** handed off to transport. #1 in queue.
  Debug: Envelope 'abb5b3e2ee3a4dbda50efe7***********' sent successfully. Payload:

Is there something I am missing?

adamsfamily
  • 1,746
  • 19
  • 37

2 Answers2

1

A few things:

  • There's nothing wrong with the way you originally implemented it. The debug logs you showed are just Sentry doing it's normal work. If you don't want to see them, don't set o.Debug = true;

  • You have code that manually reads the SENTRY_DSN environment variable and sets it to o.Dsn during initialization. That's redundant because the SDK will already look for that environment variable if you don't pass a DSN in code. Do one or the other, but not both.

  • If you were concerned about the message "Failed to report an error on a session because there is none active." - That's just saying that you haven't started a session, so Sentry's "Release Health" feature won't work. You can enable it either by manually calling SentrySdk.StartSession(); and SentrySdk.EndSession(); at appropriate places in your application, or by setting o.AutoSessionTracking = true; which is easier. The latter will start a session when the Sentry SDK is initialized, and end it when it is disposed.

  • While nothing wrong with the approach you showed, you would get better functionality out of the logging integration. The example code here shows how to use it with the generic host. Use the nuget package Sentry.Extensions.Logging.

Putting it all together :

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .ConfigureLogging(logging =>
    {
        logging.AddSentry(o =>
        {
            // o.Dsn = "(only if not using the env var)"; 
            o.TracesSampleRate = 1.0;
            o.AutoSessionTracking = true;
        });
    }
    .Build();

await host.RunAsync();
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
-2

It seems that as per the documentation the correct way to integrate Sentry with .NET (Core) 6.0 is the following: (changes indicated <--)

// Program.cs

var builder = WebApplication.CreateBuilder(args);

var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");  // <--
builder.WebHost.UseSentry(sentryDsn);                              // <--

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSentryTracing();                                            // <--

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

It does catch unhandled API call errors and it does not print any warnings on the output console.

adamsfamily
  • 1,746
  • 19
  • 37