Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog: Can I add a property without adding to the message?

Tags:

serilog

I have a WIndows .NET app, and starting to use Serilog. I initialize this like this:

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();

And I use it like this:

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

I'd like my OrderID to be displayed in the message and I'd like the order object to be included as a property (so that I can access it when I dig into this event in Seq) but I do not want the message itself to contain the object (too big). Is there a way to do this?

Or so I need something like this:

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

Seems like a lot of code...

like image 921
Ed Landau Avatar asked Nov 22 '25 12:11

Ed Landau


2 Answers

You can add anther ForContext to your logger for order object the same way you add InstrumentID and it will be included as a property

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

_log.Verbose("This is an order: {orderID}", order.OrderID);
like image 135
ElasticCode Avatar answered Nov 25 '25 11:11

ElasticCode


_log.ForContext("order", order, true).Verbose("Hit {orderID}", orderID);

The true here tells Serilog to serialized ("destructure") order instead of calling its ToString() method.

like image 41
Nicholas Blumhardt Avatar answered Nov 25 '25 11:11

Nicholas Blumhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!