我遇到过这样的情况:某些日志事件包含较大的属性值(在这种特殊情况下,是一个大的 XML 数据包)。我想使用 Serilog 的ByIncludingOnly功能为这些大数据事件使用额外的接收器。这是我认为可行的示例:
private static void FilteredLogging()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new RawFormatter())
.WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(LargeDataPackets))
.WriteTo.File("big.txt")
.CreateLogger();
Log.Information("go");
Log.ForContext("data", "12345").Information("Small packet");
Log.ForContext("data", "1234567890987654321").Information("Big packet");
Log.CloseAndFlush();
}
private static bool LargeDataPackets(LogEvent le)
{
return le.Properties.ContainsKey("data") &&
le.Properties["data"].ToString().Length > 10;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,所有三个消息都会转到“big.txt”文件。我预计只有最后一项(“大数据包”)会进入文件,因为它是属性data超过 10 个字符的唯一事件。
我正在使用 Serilog 2.0。
你的括号稍有偏差:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new RawFormatter())
.WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(LargeDataPackets))
.WriteTo.File("big.txt")
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
应该:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new RawFormatter())
.WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(LargeDataPackets)
.WriteTo.File("big.txt"))
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5747 次 |
| 最近记录: |