Advice on how to log error run on a background thread

We have an ASP.NET Core app that uses recurring jobs to run in jobs in the background that, occasionally fail due to reasons that have nothing to do with Hangfire. I would like to control how these errors are logged globally and have read all Microsoft and Serilog writings I can find on logging. Most of the Microsoft advice pertains to logging middleware, meaning it does not speak to Hangfire jobs that run in the background. Is there any Hangfire specific hook I can use to handle what gets logged when errors occur in a background job? Barring a global hook, how can I catch and log an exception and then tell Hangfire the job failed without logging another exception?

We are trying to control what gets logged and where, as errors that occur in the background currently leak too many implementation details to reports our users can view.

How the details of the exception get communicated to your users isn’t really a Hangfire problem, it’s a logging/application code problem. That being said, there’s 3 places you could hook in that would make sense (there could be more):

  1. try/catch/throw pattern where you log the level of detail you care about in your catch and then rethrow so Hangfire can continue it’s error management pipeline. This makes sense in some cases but wrapping everything in try/catches is a bit of an anti-pattern if you have better options.

  2. Global logging: You could then configure your logger to deliver your user-visible exceptions in such a way that they don’t contain the full stack trace and/or whatever else you’re trying to hide. I don’t know enough details about your problems, but I suspect this is the approach that would make the most sense.

  3. Custom Hangfire Filter for detecting errors and capturing the level of logging information you care about. If you look at this documentation plus the source code for AutomaticRetry attribute you can probably figure out how to inject your logging logic:

Hope that helps!

1 Like

Thanks, @Jonah_Simpson, option number two does solve the problem. As it turns out, however, it was application code that logged the full stack trace rather than Hangfire’s internal error handling code, so that is what truly fixed it.

The call was coming from inside the house.