.net 仅当作业重试次数用尽且作业变为失败状态时,应用程序洞察的Hangfire作业筛选器才应记录

d4so4syb  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(148)

我正在使用以下Hangfire作业过滤器在Application Insights中记录作业执行情况。我的目标是为所有重试都失败后最终失败的作业创建警报。但是,我遇到了一个问题,即Application Insights记录每个抛出的异常,即使Hangfire将要重试作业。这会导致过早警报,因为我只想在作业进入Hangfire中的“失败”选项卡时进行记录,这意味着它已经停止重试并真正失败。
下面是我用来记录作业的HangfireApplicationInsightsFilter类:

  1. public sealed class HangfireApplicationInsightsFilter : IServerFilter
  2. {
  3. private readonly TelemetryClient _telemetryClient;
  4. public HangfireApplicationInsightsFilter(TelemetryClient telemetryClient) => _telemetryClient = telemetryClient;
  5. public void OnPerforming(PerformingContext filterContext)
  6. {
  7. var operation = _telemetryClient.StartOperation<RequestTelemetry>(GetJobName(filterContext.BackgroundJob));
  8. operation.Telemetry.Properties.Add("JobId", filterContext.BackgroundJob.Id);
  9. operation.Telemetry.Properties.Add("Arguments", GetJobArguments(filterContext.BackgroundJob));
  10. filterContext.Items["ApplicationInsightsOperation"] = operation;
  11. }
  12. public void OnPerformed(PerformedContext filterContext)
  13. {
  14. if (filterContext.Items["ApplicationInsightsOperation"] is not IOperationHolder<RequestTelemetry> operation) return;
  15. if (filterContext.Exception == null || filterContext.ExceptionHandled)
  16. {
  17. operation.Telemetry.Success = true;
  18. operation.Telemetry.ResponseCode = "Success";
  19. }
  20. else
  21. {
  22. operation.Telemetry.Success = false;
  23. operation.Telemetry.ResponseCode = "Failed";
  24. var operationId = operation.Telemetry.Context.Operation.Id;
  25. var exceptionTelemetry = new ExceptionTelemetry(filterContext.Exception);
  26. exceptionTelemetry.Context.Operation.Id = operationId;
  27. exceptionTelemetry.Context.Operation.ParentId = operationId;
  28. _telemetryClient.TrackException(exceptionTelemetry);
  29. }
  30. _telemetryClient.StopOperation(operation);
  31. }
  32. private static string GetJobName(BackgroundJob backgroundJob) => $"{backgroundJob.Job.Type.Name}.{backgroundJob.Job.Method.Name}";
  33. private static string GetJobArguments(BackgroundJob backgroundJob) => JsonSerializer.Serialize(backgroundJob.Job.Args);
  34. }

字符串
这个过滤器记录每一个异常,即使是在作业被重试的时候。我需要的是只有在最后一次重试失败后才记录异常。
如何修改`HangfireApplicationInsightsFilter,使其仅在Hangfire已停止重试作业且作业已移至“Failed”状态时才记录异常?
任何关于如何实现这种行为的指导或见解将不胜感激。

snz8szmq

snz8szmq1#

你可以创建一个过滤器来实现IApplyStateFilter接口,如下所示:

  1. public sealed class HangfireApplicationInsightsFilter : IServerFilter, IApplyStateFilter
  2. {
  3. // .. the other implementations
  4. public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
  5. {
  6. Logger.DebugFormat(
  7. "Job `{0}` state was changed from `{1}` to `{2}`",
  8. context.BackgroundJob.Id,
  9. context.OldStateName,
  10. context.NewState.Name);
  11. if (context.NewState is FailedState failed)
  12. {
  13. // do something with failed state.
  14. }
  15. }
  16. }

字符串

展开查看全部

相关问题