Search code examples
c#asp.net-mvchangfireserilog

Is there a way to turn off logging that Hangfire does with serilog?


Is there a way to turn off logging that Hangfire does with serilog? We are using our own abstraction and I don’t want all this extra noise coming from the Hangfire logger while using serilog.

// INIT call under web project 
namespace MYApp.Web.App_Start
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            Core.Logging.Serilog.SetConfiguration();
        }
    }
}

// project where config method is setup

namespace MYApp.Core.Logging
{
 public static class Serilog
    {
      public static void SetConfiguration()
            {

                Log.Logger = new LoggerConfiguration()
                    //.WriteTo.File(@"c:\log-.txt", rollingInterval: RollingInterval.Minute, shared: true)
                    .WriteTo.Email(new EmailConnectionInfo()
                    {
                        FromEmail = "xxxxxx@gmail.com",
                        MailServer = "smtp.gmail.com",
                        ToEmail = "xxxx@xxxx.xx.xx",
                        NetworkCredentials = new NetworkCredential("xxxx@gmail.com", "xxxxxxxxx"),
                        Port = 587,
                        EnableSsl = true,
                        EmailSubject = "YYYYYY: Error Log"
                    }, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {NewLine} {Message:lj}{NewLine}{Exception}")
                    .Filter.ByExcluding(Matching.FromSource("Hangfire"))
                    .CreateLogger();
            }
 }
}

Solution

  • Define a logger and log provider that does not log anything:

    using Hangfire;
    using Hangfire.Logging;
    
    public class NoLoggingProvider : ILogProvider {
        public ILog GetLogger(string name) {
            return new NoLoggingLogger();
        }
    }
    
    public class NoLoggingLogger : ILog {
        public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null) {
            return false;
        }
    }
    

    and configure Hangfire to use it in your Startup class:

    using Hangfire;
    
    public class Startup {
        public void Configuration(IAppBuilder app) {
            GlobalConfiguration.Configuration.UseLogProvider(new NoLoggingProvider());
            // the rest of your configuration...        
        }
    }