你好,我试图使用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();
现在,我期望当我使用键为audit
的键值对将数据Push
到日志上下文时,我的数据将被记录在第一个模式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");
}
Map
?基本上当我有多个需要匹配的key
时,我应该使用多个Map
。 - Bercovici Adriantype
从未变成audit
,即使我在写入日志时使用了LogContext.PushProperty("type","audit")
。它们都被放置在logPath
中。 - Bercovici Adrian.Enrich.FromLogContext()
了...请阅读我回答中的最后一句话。 - C. Augusto Proiete