将 Hangfire 日志过滤成单独的 Serilog 输出

Filter Hangfire logs into separate Serilog output

Hangfire (v1.3 +) 有一个 'clever' feature,它可以在其中获取应用程序现有的日志记录设置并使用它。

Starting from Hangfire 1.3.0, you are not required to do anything, if your application already uses one of the following libraries through the reflection (so that Hangfire itself does not depend on any of them).

因为我不想将 hangfire 日志记录与我的应用程序日志混在一起,所以我想将它们过滤到一个单独的日志文件中。

Serilog has filters 可以做到这一点,但它需要过滤一些东西。

Hangfire 是否包含我可以在过滤时指定的任何有用的上下文?

我认为您可以使用的过滤器类似于:

Log.Logger = new LoggerConfiguration()
    .WriteTo.ColoredConsole()
    .Filter.ByIncludingOnly(Matching.FromSource("Hangfire"))
    .CreateLogger();

另见

我无法让 Serilog Matching.FromSource(...) 工作,Hangfire 事件似乎没有 属性。我有以下解决方案:

var logFile = "...";
var hangfireFile = "...";
var hangfireEvents = Matching.WithProperty<string>("Name", x => x.StartsWith("Hangfire"));

Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.Logger(lc =>
            lc.Filter.ByExcluding(hangfireEvents)
              .WriteTo.RollingFile(new CompactJsonFormatter(new SafeJsonFormatter()), logFile))
        .WriteTo.Logger(lc => 
            lc.Filter.ByIncludingOnly(hangfireEvents)
              .WriteTo.RollingFile(new CompactJsonFormatter(new SafeJsonFormatter()), hangfireFile))
        .CreateLogger();