我的 C# Serilog 输出应该转到两个不同的文件:使用一组表达式 (WriteOperationalLog) 时的“常规”输出,以及使用另一组表达式 (WriteJsonLog) 时的 JSON 输出。
据我了解,我认为我应该使用子记录器来过滤掉 JSON 表达式并将其发送到我的单独文件输出。每当我尝试使用过滤器时,它都会导致无限循环。
我的记录器创建函数如下所示:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(filepath, rollingInterval: RollingInterval.Day)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(WriteJsonLog)
.WriteTo.File(new ExpressionTemplate("{ @m } \n"), filepathJson, rollingInterval: RollingInterval.Day))
.CreateLogger();
如果有人可以向我指出有关如何使用 .Filter 功能的文档,那将非常有帮助,因为我自己找不到任何好的东西。
编辑:我设法弄清楚了!
我的记录器配置现在如下所示:
我们现在使用Serilog.Context
在 WriteJSONLog 函数中添加一个“JSON”属性:
using(LogContext.PushProperty("JSON", true))
{
Log.Information(json);
}
使用该Serilog.Filters
包,我们可以测试 logEvent 是否包含该 JSON 属性。我的 LoggerConfiguration 还有一些其他错误,但现在看起来像这样:
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext() //enable the loggers to add properties to our messages (to add the JSON property)
.MinimumLevel.Debug()
.WriteTo.Logger(lc => lc
.Filter.ByExcluding(Matching.WithProperty("JSON")) // Write the messages that DO NOT have the JSON property to the regular file
.WriteTo.File(filepath, rollingInterval: RollingInterval.Day))
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty("JSON")) // Write all messages that DO have the JSON property to our JSON output
.WriteTo.File(new ExpressionTemplate("{ @m } \n"), filepathJson, rollingInterval: RollingInterval.Day)) //message formatting to only output the string, no extras
.CreateLogger();