有条件地分别禁用Serilog接收器

时间:2019-09-09 03:58:10

标签: .net-core serilog

我在.net核心应用基本配置上有serilog,如下所示:-

setTimeout(function() {    
   var DataTable = $(".dataTable").DataTable();
   DataTable.columns.adjust().responsive.recalc();
}, 300);

现在让我们说我希望根据条件写入SomeOtherLog。那怎么办?

类似

Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day, outputTemplate: LOG_TEMPLATE)
        .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate)
        .WriteTo.SomeOtherLog()
        .CreateLogger();

2 个答案:

答案 0 :(得分:2)

var configuration = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day,
                      outputTemplate: LOG_TEMPLATE)
        .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate);

if (condition)
{
    configuration.WriteTo.SomeOtherLog();
}

Log.Logger = configuration.CreateLogger();

答案 1 :(得分:1)

Serilog 2.9.0开始,您现在可以使用.WriteTo.Conditional并指定定义是否将接收器写入信宿的条件。

Log.Information("Hello");
Log.CloseAndFlush();

var configuration = new LoggerConfiguration()
    .ReadFrom.Configuration(Configuration)
    .Enrich.FromLogContext()
    .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day,
        outputTemplate: LOG_TEMPLATE)
    .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate)
    .WriteTo.Conditional(evt => condition, wt => wt.SomeOtherLog());

Log.Logger = configuration.CreateLogger();
// ...