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

问题描述 投票:2回答:3

我有一个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);
}

好像很多代码......

serilog
3个回答
1
投票

您可以像添加ForContext一样在qazxsw poi对象的记录器中添加另一个qazxsw poi,它将作为属性包含在内

order

0
投票

是的,但是InstrumentID


和例子:

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

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

消费如此:

there are weird tricks involved

当然,您也可以从class ScalarValueEnricher : ILogEventEnricher { readonly LogEventProperty _prop; public ScalarValueEnricher(string name, object value) { _prop = new LogEventProperty(name, new ScalarValue(value)); } public void Enrich(LogEvent evt, ILogEventPropertyFactory _) { evt.AddPropertyIfAbsent(_prop); } } 制作临时工具,其中更清洁/更清晰/更高效。


0
投票
var _log = Log.ForContext<GameBase>()
    .ForContext("InstrumentID", InstrumentId);

_log.ForContext(new ScalarEnricher("order",order)).Verbose("Hit: {orderID}", order.OrderID);

这里的_log.ForContext(new ScalarEnricher("order",order))告诉Serilog序列化(“destructure”)_log.ForContext("order", order, true).Verbose("Hit {orderID}", orderID); 而不是称它的true方法。

© www.soinside.com 2019 - 2024. All rights reserved.