Serilog:我可以在不添加到消息的情况下添加属性吗?

标签 serilog

我有一个 WIndows .NET 应用程序,并开始使用 Serilog。 我这样初始化它:

Log.Logger = new LoggerConfiguration()
  .MinimumLevel.Verbose()
.Enrich.With(new ThreadIdEnricher())
.Enrich.WithProperty("BuildId", Guid.NewGuid()) // One Guid per run.
.Enrich.FromLogContext()
.WriteTo.RollingFile(@"C:\QRT\Logs\QRT-LOG.txt", LogEventLevel.Verbose)
.WriteTo.Seq("http://localhost:5341" )
.WriteTo.Console(outputTemplate:"{Source} BLAHBLAH {Message:lj}")
.WriteTo.File(new CompactJsonFormatter(), "C:/QRT/Logs/log.json")
.CreateLogger();

我是这样使用它的:

_log = Log.ForContext<GameBase>()
.ForContext("InstrumentID", InstrumentId);
_log.Verbose("This is an order: {orderID} / {order}", order.OrderID, order);

我希望我的 OrderID 显示在消息中,我希望将订单对象作为属性包含在内(这样当我在 Seq 中深入了解此事件时我可以访问它)但我不想消息本身包含对象(太大)。有办法做到这一点吗?

或者我需要这样的东西:

using (var __log = _log.PushProperty("order", order)
{
  __log.Verbose ("Hit {orderID}", orderID);
}

代码好像很多...

最佳答案

您可以像添加 InstrumentID 一样将 ForContext 添加到 order 对象的记录器中,它将作为属性包含在内

_log = Log.ForContext<GameBase>()
    .ForContext("InstrumentID", InstrumentId)
    .ForContext("Order", order, true);

_log.Verbose("This is an order: {orderID}", order.OrderID);

关于Serilog:我可以在不添加到消息的情况下添加属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55101757/

相关文章:

记录到 Blazor WASM 中的文件

docker - 将Seq日志持久保存到EBS卷-该卷不断分离

c# - 记录可能为空参数时 Log.Information 和 Log.Logger.Information 之间的 Serilog 差异

c# - Serilog:记录不同类型的日志事件

elasticsearch - Serilog输出到文件和Elasticsearch的最佳方法

c# - Serilog - 多个日志文件

serilog - 如何让 Serilog 实例立即登录到 Seq 而不必调用它的 Dispose()?

c# - Serilog 不会在 MongoDB 上写入,也不会抛出任何错误

c# - 程序类中的 Serilog

c# - 带有Kibana的ElasticSearch云上的Serilog接收器未收到消息