How can I add a named property that is not part of the message template?

会有一股神秘感。 提交于 2019-12-10 17:09:32

问题


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


回答1:


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)



来源:https://stackoverflow.com/questions/30637416/how-can-i-add-a-named-property-that-is-not-part-of-the-message-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!