Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging the execution of a Hangfire RecurringJob in database?

I have set up hangfire successfully for my ASP.NET project, i.e. the 11 Hangfire tables are created in my database. I tried the following command inside the Application_Start() of my project's Global.asax:

namespace myAPI
{
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start(
      {
         System.Diagnostics.Debug.WriteLine("Recurring job will be set up.");

         RecurringJob.AddOrUpdate(
             "some-id", 
             () => System.Diagnostics.Debug.WriteLine("Job instance started at " +
                                                      DateTime.Now)),
             "*/2 * * * 1-5"); 
      }
   }
}

Sadly, inside Visual Studio's window Output > Debug I only see Reccuring job will be set up. and nothing ever after. However, a SELECT * FROM [myContext].[HangFire].[Set] shows me

Key              Score      Value     ExpireAt
recurring-jobs  1579116240  some-id   NULL

So far so good, this means that the job is indeed set up.

But how do I log inside my DB each and each time when the RecurringJob is executed? Do I assume correctly that Hangfire does not do that out of the box and I have to log it myself within the arrow-function? Or is there a more elegant way?

Question on the side: Why don't I see any output of System.Diagnostics.Debug.WriteLine within my recurring job?

References

  • Hangfire doesn't create tables in IIS
  • How to configure hangfire with ASP.NET to obtain connection string from config file?
  • Official hangfire.io docu on recurrent tasks
like image 879
B--rian Avatar asked Jan 26 '23 10:01

B--rian


1 Answers

You can use SeriLog with Hangfire out of the box. Serilog comes with different sinks, e.g. Serilog.Sinks.MSSqlServer. You can configure it in startup.cs:

using Serilog;
using Serilog.Sinks.MSSqlServer;

Log.Logger = new LoggerConfiguration()
                 .WriteTo
                 .MSSqlServer(
                        connectionString: hangfireConnectionString,
                        tableName: "Logs",
                        autoCreateSqlTable: true
                    ).CreateLogger();
               // will display any issues with Serilog config. comment out in prod.
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

GlobalConfiguration.Configuration
                   .UseSqlServerStorage(hangfireConnectionString)
                   .UseSerilogLogProvider();

After you schedule your job, you can log it with

Log.Information(string.Format("Hanfire Job Scheduled at {0}", DateTime.Now));
like image 68
salli Avatar answered Jan 28 '23 15:01

salli