Serilog - 无法根据属性记录到多个文件

2024-01-31

您好,我正在尝试使用以下命令在一个文件中记录一些消息,在另一个文件中记录其他消息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");
} 

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

Update

从下面的答案中我了解到不需要定义多个记录器,而是根据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");
}

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

根据价值决定选择水槽type财产必须由您在主体中完成Map配置。

e.g.

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() above.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Serilog - 无法根据属性记录到多个文件 的相关文章

随机推荐