0

I would like to do this:

logger.LogInformation($"Calling {nameof(MyMethod)} for message {messageId}", messageId);

So far it seems not possible to combine syntax for structured logging with interpolated string. Maybe I am missing something here and there is syntax for that?

P.S. I want the first argument interpolated, but the latter be used in structured logging.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • why do you want that? String-interpolation is usually used to *avoid* using `String.Format`. If you really want to different syntaxes, then split your string into two literal:s `$"..." + String.Format("...")`. – MakePeaceGreatAgain Dec 06 '21 at 14:23
  • This is not an ordinary string format, it is used for structured logging, so that `messageId` would be both a part of the message and a separate field in the logging storage – Ilya Chernomordik Dec 06 '21 at 14:26
  • Why do you want this? If you don't want to use the first argument, don't use it. Both will be emitted so you aren't losing anything. You can still filter by the message template and the method name. One could argue that you gain nothing with `nameof(MyMethod)`. The event you log isn't tied to the method name, and logging isn't meant for activity tracing either, although it's often used for this – Panagiotis Kanavos Dec 06 '21 at 14:28
  • 1
    In any case you can escape curly braces by doubling them ,eg `" {{messageId}} "` – Panagiotis Kanavos Dec 06 '21 at 14:29
  • I don't want to hardcode the name of the MyMethod in case it will change in the future, so I want to interpolate it and I want the messageId to be in structured logging. I'll try with double curly, thanks for suggestion. I also don't want the name of the method in the structured logging as it adds nothing, but it's not a big deal I suppose if it will be added as well – Ilya Chernomordik Dec 06 '21 at 14:31
  • 2
    You can also use a `IFormattable` parameter and handle string interpolation yourself. This allows you to access the parameters of the interpolated string (e.g. `messageId`) without having to repeat parameters as plain method parameters. See: [Customizing string interpolation in C# 6](https://thomaslevesque.com/2015/02/24/customizing-string-interpolation-in-c-6/) – Olivier Jacot-Descombes Dec 06 '21 at 15:01

0 Answers0