通过应用洞察力跟踪hangfire后台作业

时间:2020-06-30 07:43:22

标签: asp.net-core hangfire telemetry appinsights

我已经在Asp.net核心应用程序中建立了应用程序见解。我所有的Web API请求都根据应用程序见解进行跟踪,如果遇到任何故障,我可以在Failures部分中找到它们。

app insights

但是,我也正在运行Hangfire后台作业,如果它们失败了,我就无法在应用程序见解中找到它们。另外,我有警报规则Whenever the total http server errors is greater than or equal to 1 count,并且不确定在这种情况下hangfire 5xx错误是否会发生。

那么有什么方法可以跟踪Hangfire作业失败并得到通知吗?

1 个答案:

答案 0 :(得分:0)

Hangfire可以处理大多数异常,因此App Insights不会默认接收它们。您还需要对App Insights进行大量配置。

我为Hangfire编写了一个JobFilter,可让您与App Insights建立联系,这足以使您前进: https://github.com/maitlandmarshall/MAD.Integration.Common/blob/master/MAD.Integration.Common/Analytics/AppInsightsEventsFilter.cs

对于App Insights配置: https://github.com/maitlandmarshall/MAD.Integration.Common/blob/master/MAD.Integration.Common/Analytics/TelemetryConfigurationFactory.cs

通过以上链接将所有内容组合在一起:

var appInsights = this.rootScope.ResolveOptional<AppInsightsConfig>();
var childScope = ServiceScope = this.rootScope.BeginLifetimeScope("HangfireServiceScope");
var activator = new AutofacLifecycleJobActivator(childScope);
var options = new BackgroundJobServerOptions()
{
    Activator = activator,
    Queues = new[] { JobQueue.Alpha, JobQueue.Beta, JobQueue.Default, JobQueue.Low }
};

this.globalConfig
    .UseFilter(new BackgroundJobContext());

if (!string.IsNullOrEmpty(appInsights?.InstrumentationKey))
{
    var telemetryClient = new TelemetryClient(TelemetryConfigurationFactory.Create(appInsights));
    this.globalConfig.UseFilter(new AppInsightsEventsFilter(telemetryClient));
}

using (var server = new BackgroundJobServer(options))
{
    await server.WaitForShutdownAsync(stoppingToken);
}