6
votes

Im new to hangfire, and im trying to setup a way to log the events using my existing serilog logger in an asp.net web api. Here is my logger class:

public static class LoggerInitializer
{
    private static ILogger CreateLog()
    {
        var settings = Settings.Instance;
        Log.Logger = new LoggerConfiguration().
            MinimumLevel.Debug().
            WriteTo.RollingFile(settings.LoggerDebugDirectory +"Debug-{Date}.txt", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug, 
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}").
            WriteTo.RollingFile(settings.LoggerVerboseDirectory + "Debug-{Date}.txt").
            CreateLogger();
        return Log.Logger;
    }
    static ILogger _logger;
    public static ILogger GetLogger()
    {
        if (_logger != null)
            return _logger;
        return _logger = CreateLog();
    }
}

and in my startup file I add the code from the hangfire documentation:

GlobalConfiguration.Configuration
            .UseSqlServerStorage(Settings.Instance.NLSContextConnectionString);

        app.UseHangfireDashboard();
        app.UseHangfireServer();

My hangfire works perfectly, but how do i enable make hangfire use my serilog?

2
According to the documentation, Hangfire automatically supports logging to Serilog. Is that not working for you? - PatrickSteele
no it is not, sadly. and i find the documentation really lacking. - Jonas Olesen
Unrelated to your issue, but the lack of a Log.CloseAndFlush() call at application exit will cause problems (unless it's simply omitted from your code sample). Cheers! - Nicholas Blumhardt

2 Answers

2
votes

It's possible that Hangfire is initializing and caching its own internal logger before CreateLog() is being called by the application.

To test this theory, try moving the code that initializes Log.Logger to the very beginning of the app's startup code, e.g. in Global.Application_Start() or similar.

1
votes

In Hangfire 1.6.19 (and maybe before that, I did not check) adding the NuGet Package to your project gives you an extension method on IGlobalConfiguration :

configuration.UseSerilogLogProvider();