Using job filters¶

All processes are implemented with Chain-of-responsibility pattern and can be intercepted like with ASP.NET MVC Action Filters.

Define the filter

  1. public class LogEverythingAttribute : JobFilterAttribute,
  2. IClientFilter, IServerFilter, IElectStateFilter, IApplyStateFilter
  3. {
  4. private static readonly ILog Logger = LogProvider.GetCurrentClassLogger();
  5.  
  6. public void OnCreating(CreatingContext context)
  7. {
  8. Logger.InfoFormat("Creating a job based on method `{0}`...", context.Job.Method.Name);
  9. }
  10.  
  11. public void OnCreated(CreatedContext context)
  12. {
  13. Logger.InfoFormat(
  14. "Job that is based on method `{0}` has been created with id `{1}`",
  15. context.Job.Method.Name,
  16. context.BackgroundJob?.Id);
  17. }
  18.  
  19. public void OnPerforming(PerformingContext context)
  20. {
  21. Logger.InfoFormat("Starting to perform job `{0}`", context.BackgroundJob.Id);
  22. }
  23.  
  24. public void OnPerformed(PerformedContext context)
  25. {
  26. Logger.InfoFormat("Job `{0}` has been performed", context.BackgroundJob.Id);
  27. }
  28.  
  29. public void OnStateElection(ElectStateContext context)
  30. {
  31. var failedState = context.CandidateState as FailedState;
  32. if (failedState != null)
  33. {
  34. Logger.WarnFormat(
  35. "Job `{0}` has been failed due to an exception `{1}`",
  36. context.BackgroundJob.Id,
  37. failedState.Exception);
  38. }
  39. }
  40.  
  41. public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
  42. {
  43. Logger.InfoFormat(
  44. "Job `{0}` state was changed from `{1}` to `{2}`",
  45. context.BackgroundJob.Id,
  46. context.OldStateName,
  47. context.NewState.Name);
  48. }
  49.  
  50. public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
  51. {
  52. Logger.InfoFormat(
  53. "Job `{0}` state `{1}` was unapplied.",
  54. context.BackgroundJob.Id,
  55. context.OldStateName);
  56. }
  57. }

Apply it

Like ASP.NET filters, you can apply filters on method, class and globally:

  1. [LogEverything]
  2. public class EmailService
  3. {
  4. [LogEverything]
  5. public static void Send() { }
  6. }
  7.  
  8. GlobalJobFilters.Filters.Add(new LogEverythingAttribute());

原文:

http://docs.hangfire.io/en/latest/extensibility/using-job-filters.html