我综合了Sentry
与 .NET Core 6.0工人服务这边走:
NuGet: 哨兵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);
}
}
}
这在某种程度上是有效的,因为我在我的 Sentry 仪表板上看到了手动捕获的错误。但是,我担心在应用程序输出上收到的这些警告消息:
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:
我有什么遗漏的吗?
一些东西:
-
您最初实现它的方式没有任何问题。您显示的调试日志只是 Sentry 正在正常工作。如果您不想看到它们,请不要设置o.Debug = true;
-
您有手动读取的代码SENTRY_DSN
环境变量并将其设置为o.Dsn
在初始化期间。这是多余的,因为 SDK 会already如果您未在代码中传递 DSN,请查找该环境变量。执行其中之一,但不要同时执行两者。
-
如果您担心该消息"Failed to report an error on a session because there is none active."
- 这只是说您还没有开始会话,所以 Sentry 的“释放生命值 https://docs.sentry.io/product/releases/health/" 功能将不起作用。您可以通过手动调用来启用它SentrySdk.StartSession();
and SentrySdk.EndSession();
在应用程序中适当的位置,或者通过设置o.AutoSessionTracking = true;
这更容易。后者将在 Sentry SDK 初始化时启动会话,并在释放时结束会话。
-
虽然您展示的方法没有任何问题,但您可以从中获得更好的功能日志集成 https://docs.sentry.io/platforms/dotnet/guides/extensions-logging/。示例代码here https://github.com/getsentry/sentry-dotnet/blob/9f7caf11366ef2d73346e7c176ff2478a6904455/samples/Sentry.Samples.GenericHost/Program.cs显示如何将其与通用主机一起使用。使用 nuget 包Sentry.Extensions.Logging https://www.nuget.org/packages/Sentry.Extensions.Logging.
把它们放在一起:
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)