【问题标题】:Serilog - can not log to multiple files based on propertySerilog - 无法根据属性记录到多个文件
【发布时间】:2020-07-09 14:53:43
【问题描述】:

您好,我正在尝试使用Serilog 将一些消息记录在一个文件中,而将其他消息记录在另一个文件中。

我尝试了以下配置:

Log.Logger = new LoggerConfiguration()
                    .WriteTo.Map("type", "audit", (name, x) => x.File(auditLogPath))
                    .WriteTo.Map("type", "normal", (nm, wt) => wt.File(logpath).WriteTo.Console())
                    .CreateLogger();

现在我期待当我Push 一个键为audit 的键值对到日志上下文时,我的数据将记录在第一个模式audit

using(LogContext.PushProperty("type","audit")
{
    Log.Information("something");
} 

为什么我的数据会进入第二种模式?它被记录到控制台并放入另一个文件,我不明白为什么。

更新

从下面的答案我了解到没有必要定义多个记录器,而是基于key 调度:

Log.Logger = new LoggerConfiguration()
                  .WriteTo.Map("type", string.Empty, (nm, wt) => {
                      if (nm == "audit") {
                        wt.File(auditLogPath);  //i want to write here !
                        return;
                      }
                      wt.File(logpath).WriteTo.Console()                                                                                
                   })
             .CreateLogger();

但是,当我尝试使用它登录第一个场景 audit 时,所有日志都放在另一个场景中(logpath+ Console

using(LogContext.PushProperty("type","audit"))
{
    Log.Information("something");
}

【问题讨论】:

    标签: asp.net-core logging serilog rollingfilesink


    【解决方案1】:

    你误解了Map的第二个参数是什么。它不是过滤器...它只是您的 keyPropertyName 的默认值,以防日志事件中不存在。

    根据type 属性的值选择接收器的决定必须由您在Map 配置的主体中完成。

    例如

    Log.Logger = new LoggerConfiguration()
        .WriteTo.Map("type", string.Empty, (type, wt) =>
        {
            if (type.Equals("audit"))
            {
                wt.File(auditLogPath);
            }
            else if (type.Equals("normal"))
            {
                wt.File(logPath)
                    .WriteTo.Console();
            }
        })
        .Enrich.FromLogContext()
        .CreateLogger();
    

    另请注意,如果不通过LogContext 启用丰富,Map 将看不到您推送的属性,因此您需要上面的.Enrich.FromLogContext()

    【讨论】:

    • 所以你是说我不需要使用Map 两次?基本上,当我有多个需要匹配的key-s 时,我应该使用多个Map
    • @BercoviciAdrian 正确
    • 所以我使用了您提供的配置,但不知何故,委托中的type 永远不会得到audit,即使我在写入记录器时使用LogContext.PushProperty("type","audit")。它们都被放入@ 987654335@.
    • 您忘记添加.Enrich.FromLogContext() ...阅读我回答中的最后一句话
    猜你喜欢
    • 2022-01-26
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2013-05-25
    • 2012-11-18
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多