How to add a parameter to .Net Core structured logging without referencing it in a message?
Asked Answered
V

1

7

I can do this in .net core

_logger.LogInformation("Token validated {clientId}", "MyId");

And then logging libraries like NLog will know that there is a property called clientId with the value MyId in the message and can render it in a special way.

I am trying to do the same without including the property in the message itself, but cannot manage to nail it. This is what I have done so far and it does not result in a property in NLog:

 LogEventInfo info = new LogEventInfo
 {
    Properties = {{"clientId", "MyId"}},
 };
 _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "Token validated", info, null, info.MessageFormatter);

This results in a message without property. Is there a better way to do this or have I done something wrong?

Vellicate answered 28/10, 2019 at 9:20 Comment(0)
J
4

The whole idea with Microsoft-Extension-Logging (MEL) ILogger-interface is not being dependent on a specific Logging-Framework.

If you start creating NLog LogEventInfo-objects, then you might as well call NLog.LogManager.GetCurrentClassLogger() and use that as Logger.

But maybe this wiki-page can give you some ideas:

https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging

Jeff answered 28/10, 2019 at 16:4 Comment(4)
Hi, yes, thanks for the answer. I did not really understand that LogEventInfo was from NLog and not from MS itself. So I suppose I just need to follow the pattern and create my own? It's a bit strange there is no easy way to just send parameters...Vellicate
@IlyaChernomordik The link in my answer shows how you can introduce custom properties. And you can also cheer for this issue: github.com/aspnet/Extensions/issues/668Jeff
Thanks, it's been 3 years though without progress on the issue :)Vellicate
@IlyaChernomordik I can see a code-example at the bottom of the issue, that is official "solution" from the official Microsoft-developer. Similar to the code examples in the wiki-page-link in my answer. But it is strange that structured logging at Microsoft means always with message-template.Jeff

© 2022 - 2024 — McMap. All rights reserved.