2

The following was taken from this Microsoft document.

_logger.LogInformation("Queued Background Task {Guid} is running. " +
                    "{DelayLoop}/3", guid, delayLoop);

What is this type of string formatting? In other words what is it called and where is it documented? Is it .NET or does it require a third party library?

10
  • It's called interpolation, learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
    – Charleh
    Dec 1, 2020 at 12:18
  • 6
    @Charleh: No it's not. Note the lack of a $ sign.
    – Jon Skeet
    Dec 1, 2020 at 12:19
  • I assume the special format will be interpreted in the LogInformation method. That's not related to normal string formatting.
    – imsmn
    Dec 1, 2020 at 12:20
  • Its a custom implementation of the String.Format, but it works with the logger. String interpolation is used with the $ sign and converts a variable value to a string. Its from microsoft but with the logger
    – nalnpir
    Dec 1, 2020 at 12:20
  • @imsmn: That is indeed the only possible explanation, but there seems to be a lack of connection between the {name} used and the values being passed. I guess we need to see the LogInformation method to rule out that some arbitrary magic values have been used, but they would be oddly specific arbitrary magic values.
    – Flater
    Dec 1, 2020 at 12:21

2 Answers 2

9

It's ASP.NET Core logging - or more generally, logging via Microsoft.Extensions.Logging.Abstractions.

Although it looks a bit like C# interpolated string literals, the message is actually formatted by the logging infrastructure. The string is a message template. The names specified in the message template are entirely independent of the expressions provided later - but the order of the placeholders is expected to be the order of the values provided.

This allows logging provides to extract key/value pairs to perform structural logging... so for example you could end up with a log entry in JSON like this:

{
  "message": "Queued Background Task 1234-5678[...] is running. 100/3",
  "properties": {
    "Guid": "1234-5678[...]",
    "DelayLoop": 100
  }
}

(It depends on the logging provider.)

2
  • I'll say that the parameters must be in the same order that they appear in the {...} templates, so "Queued Background Task {Guid} is running. {DelayLoop}/3", delayLoop, guid wouldn't work correctly
    – xanatos
    Dec 1, 2020 at 12:40
  • @xanatos: Good plan, will mention that.
    – Jon Skeet
    Dec 1, 2020 at 13:54
0

I believe this is built-in string formatting of this special library. It's look like C# interpolated string but it's not C# interpolated. The library itself append the strings and parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.