Log hangfire events using existing serilog
Asked Answered
S

2

8

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?

Spindry answered 20/9, 2016 at 8:27 Comment(3)
According to the documentation, Hangfire automatically supports logging to Serilog. Is that not working for you?Dimercaprol
no it is not, sadly. and i find the documentation really lacking.Spindry
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!Duffer
D
2

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.

Duffer answered 20/9, 2016 at 23:25 Comment(0)
A
2

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

Aimee answered 26/3, 2019 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.