我正在使用以下Hangfire作业过滤器在Application Insights中记录作业执行情况。我的目标是为所有重试都失败后最终失败的作业创建警报。但是,我遇到了一个问题,即Application Insights记录每个抛出的异常,即使Hangfire将要重试作业。这会导致过早警报,因为我只想在作业进入Hangfire中的“失败”选项卡时进行记录,这意味着它已经停止重试并真正失败。
下面是我用来记录作业的HangfireApplicationInsightsFilter类:
public sealed class HangfireApplicationInsightsFilter : IServerFilter
{
private readonly TelemetryClient _telemetryClient;
public HangfireApplicationInsightsFilter(TelemetryClient telemetryClient) => _telemetryClient = telemetryClient;
public void OnPerforming(PerformingContext filterContext)
{
var operation = _telemetryClient.StartOperation<RequestTelemetry>(GetJobName(filterContext.BackgroundJob));
operation.Telemetry.Properties.Add("JobId", filterContext.BackgroundJob.Id);
operation.Telemetry.Properties.Add("Arguments", GetJobArguments(filterContext.BackgroundJob));
filterContext.Items["ApplicationInsightsOperation"] = operation;
}
public void OnPerformed(PerformedContext filterContext)
{
if (filterContext.Items["ApplicationInsightsOperation"] is not IOperationHolder<RequestTelemetry> operation) return;
if (filterContext.Exception == null || filterContext.ExceptionHandled)
{
operation.Telemetry.Success = true;
operation.Telemetry.ResponseCode = "Success";
}
else
{
operation.Telemetry.Success = false;
operation.Telemetry.ResponseCode = "Failed";
var operationId = operation.Telemetry.Context.Operation.Id;
var exceptionTelemetry = new ExceptionTelemetry(filterContext.Exception);
exceptionTelemetry.Context.Operation.Id = operationId;
exceptionTelemetry.Context.Operation.ParentId = operationId;
_telemetryClient.TrackException(exceptionTelemetry);
}
_telemetryClient.StopOperation(operation);
}
private static string GetJobName(BackgroundJob backgroundJob) => $"{backgroundJob.Job.Type.Name}.{backgroundJob.Job.Method.Name}";
private static string GetJobArguments(BackgroundJob backgroundJob) => JsonSerializer.Serialize(backgroundJob.Job.Args);
}
字符串
这个过滤器记录每一个异常,即使是在作业被重试的时候。我需要的是只有在最后一次重试失败后才记录异常。
如何修改`HangfireApplicationInsightsFilter,使其仅在Hangfire已停止重试作业且作业已移至“Failed”状态时才记录异常?
任何关于如何实现这种行为的指导或见解将不胜感激。
1条答案
按热度按时间snz8szmq1#
你可以创建一个过滤器来实现
IApplyStateFilter
接口,如下所示:字符串