13

In some cases, I would like to add contextual information to a message (for instance currently authenticated user), without having to include it in the message template.

I would like to accomplish this :

logger.Information("Doing stuff {Foo} with the thing {Bar}. {User}", foo, bar, user)

but without the {User} in the template.

I already know about LogContext but that seems overkill when adding contextual information to just one event.

I also know I can use the low-level API logger.Write(LogEvent evnt) to actually control which properties are included, but that seems like a bit too much code for what I am trying to accomplish.

I'm pretty sure there is a short and elegant way that is super obvious, but I haven't found it :)

UPDATE :

I found out only afterwards that this question is more or less similar : Add custom properties to Serilog

Community
  • 1
  • 1
tsimbalar
  • 5,790
  • 6
  • 37
  • 61
  • Does this answer your question? [Add custom properties to Serilog](https://stackoverflow.com/questions/27888715/add-custom-properties-to-serilog) – Christian Davén Nov 05 '19 at 06:14

2 Answers2

11

I could figure it out on my own!

You can use the fluent method .ForContext(propertyName, propertyValue) on a single call to one of the .LogXXX() methods.

For instance :

logger.ForContext("User", user)
      .Information("Doing stuff {Foo} with the thing {Bar}", foo, bar)

The property added to the event only apply to the event, and they are no longer present on the next call to the logger.LogXXX() method

UPDATE

The article by Nicholas Blumhardt explains it quite well : Context and correlation – structured logging concepts in .NET (5)

tsimbalar
  • 5,790
  • 6
  • 37
  • 61
11

If you're using the generic Microsoft ILogger you can use BeginScope;

using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName",  userName } }))
{
    _logger.LogInformation(message, args);
}

This is discussed here; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/

Josh
  • 3,442
  • 2
  • 23
  • 24
  • 3
    Not sure why this isn't upvoted more. I would prefer to use ILogger interface than be tightly coupled to Serilog (although Serilog is awesome). – triple.vee Aug 31 '21 at 01:49
  • 1
    Even though the question has a #serilog tag, this approach may be more preferable, since, as mentioned by @triple.vee, it removes the need to hard-wire Serilog dependency into your logging code. – MÇT Feb 08 '22 at 09:53
  • This adds the property to the properties object, is it possible to have as an independent property? – Nemavhidi Mar 08 '22 at 07:24
  • As cool as Serilog is, I too prefer ILogger. I am in the process of switching to Serilog from Log4Net and am glad I used a façade for Log4Net, so the switch is easier. Ilogger serves the same purpose as my façade did. – Louise Eggleton Sep 13 '22 at 17:34