Custom Logging of Uncaught Exceptions

Hi, we are trying to implement our own logging in Hangfire so that we can log uncaught exceptions. While our provide does seem to be being used, it’s not being called when we enqueue a background job that simply throws a new ApplicationException(). Any guidance on what we may be doing wrong?

       public class MyHangfireLogProvider : ILogProvider
        {
            private readonly string _apiKey;
            public MyHangfireLogProvider(string apiKey)
            {
                _apiKey = apiKey;
            }
            public ILog GetLogger(string name)
            {
                return new MyHangfireLog(_apiKey);
            }
        }

    public class MyHangfireLog : ILog
        {
            private readonly string _apiKey;

            public MyHangfireLog(string apiKey)
            {
                _apiKey = apiKey;
            }

            public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null)
            {
                if(exception != null)
                {
                    var client = new RaygunClient(_apiKey);
                    client.Send(exception, null, null);
                }

                return true;
            }
        }

LogProvider.SetCurrentLogProvider(new MyHangfireLogProvider(ConfigurationService.RaygunConfiguration.ApiKey));

do you have automatic retry on the job? Hangfire logs the exception only if the job crashes on the last ‘try’. I think default is 10 tries.

We have it set to [AutomaticRetry(Attempts = 0)].

The job ends up in the “Failed” section on the Hangfire dashboard.

Turns out we implemented a new hangfire filter to log exceptions. When we called LogProvider.GetCurrentClassLogger() it still returned the NoOpLogger, instead of our logger that we set using LogProvider.SetCurrentLogProvider(). This seems like a bug to us, but maybe one of the contributors can chime in.

We ended up using the example at http://docs.hangfire.io/en/latest/extensibility/using-job-filters.html to create a new filter and apply it globally. Instead of getting the current logger using LogProvider.GetCurrentClassLogger() we had to just manually create a new instance of our logger.