Jonas Olesen
Jonas Olesen

Reputation: 568

Log hangfire events using existing serilog

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?

Upvotes: 8

Views: 5860

Answers (2)

Richard
Richard

Reputation: 662

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();

Upvotes: 2

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31832

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.

Upvotes: 2

Related Questions