HangfireIO / Hangfire

An easy way to perform background job processing in .NET and .NET Core applications. No Windows Service or separate process required
https://www.hangfire.io
Other
9.44k stars 1.71k forks source link

Hangfire logging not working with Serilog #2303

Open shaliake opened 1 year ago

shaliake commented 1 year ago

Hello!

I have added Hangfire to my solution which uses Serilog as Logger. Serilog config:

 "Serilog": {
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Hangfire": "Debug"
            }
        },
        "WriteTo:Console": {
            "Name": "Console"
        }
    }

Hangfire registration:

services.AddHangfire((provider, config) =>
        {
            config
                .UseSerilogLogProvider()
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseMongoStorage(connectionString,
                    serviceConfiguration.DatabaseName,
                    new MongoStorageOptions()
                    {
                        CheckQueuedJobsStrategy = CheckQueuedJobsStrategy.TailNotificationsCollection,
                        MigrationOptions = new MongoMigrationOptions
                        {
                            MigrationStrategy = new MigrateMongoMigrationStrategy(),
                            BackupStrategy = new CollectionMongoBackupStrategy()
                        },
                        CheckConnection = true
                    });
        });
        services.AddHangfireServer();

But still I do not see any failed job logs, only what hangfire does, is there any way to log that exception occurred during job?

[08:22:32 DBG] 1 scheduled job(s) processed by scheduler.
[08:22:46 DBG] Server 49hhvv3:31684:15d09f3e heartbeat successfully sent
[08:22:49 DBG] 1 scheduled job(s) processed by scheduler.
brgrz commented 1 year ago

This is the setup I use you might want to try that:

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .Enrich.WithProperty("AppName", appName)
                .Enrich.WithEnvironmentName()
                .Enrich.FromLogContext()
                .Enrich.FromGlobalLogContext()
                .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
                .WriteTo.PostgreSQL(dbConnString, LogsTableName, SerilogSettings.GetLogsTableDefinition(), needAutoCreateTable: true, restrictedToMinimumLevel: LogEventLevel.Information)
                .CreateLogger();

Also you need to catch exceptions inside your jobs and use injected logger to log them:

public class NotificationJob
{
    private readonly ILogger<NotificationJob> _logger;

    public TelekomSmsNotificationJob(ILogger<NotificationJob> logger )
    {
        _logger = logger;
        LogContext.PushProperty("Job", nameof(NotificationJob));
    }
    ...
    _logger.LogInformation("Sending/scheduling SMS: {@MessageBody}", smsPacket);
}