Serilog LogContext 和自定义参数不结合
Serilog LogContext and custom args don't combine
有没有办法混合自定义 serilog args 和 LogContext 属性?我已经查看了文档,但似乎没有提到它。
static void Main()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.LiterateConsole(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} [{Properties}]{NewLine}")
.CreateLogger();
using (LogContext.PushProperty("A", 5))
{
Log.Information("Message using context {A}");
var b = 1;
Log.Information("Message usign context {A} and custom {b}", b);
}
Console.ReadLine();
}
输出
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 1 and custom {b} [{}]
预期输出
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 5 and custom 1 [{}]
有什么办法可以实现吗?
在 Serilog 的 API 中,任何接受消息模板的方法都需要精确数量的匹配参数。
如果模板中的占位符数量和提供的参数计数不匹配,Serilog 不会崩溃,但不能保证这会按预期工作 - 正如您在此处看到的。
所以在这种情况下,有必要在 Information()
的参数中包含 A
和 b
以获得您期望的输出。
有没有办法混合自定义 serilog args 和 LogContext 属性?我已经查看了文档,但似乎没有提到它。
static void Main()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.LiterateConsole(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} [{Properties}]{NewLine}")
.CreateLogger();
using (LogContext.PushProperty("A", 5))
{
Log.Information("Message using context {A}");
var b = 1;
Log.Information("Message usign context {A} and custom {b}", b);
}
Console.ReadLine();
}
输出
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 1 and custom {b} [{}]
预期输出
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 5 and custom 1 [{}]
有什么办法可以实现吗?
在 Serilog 的 API 中,任何接受消息模板的方法都需要精确数量的匹配参数。
如果模板中的占位符数量和提供的参数计数不匹配,Serilog 不会崩溃,但不能保证这会按预期工作 - 正如您在此处看到的。
所以在这种情况下,有必要在 Information()
的参数中包含 A
和 b
以获得您期望的输出。