H2ONaCl
H2ONaCl

Reputation: 11269

What is the nature of this C# string formatting?

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?

Upvotes: 6

Views: 1244

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500615

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 providers to extract key/value pairs to perform structured 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.)

Upvotes: 12

Hamid Razeghi
Hamid Razeghi

Reputation: 69

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.

Upvotes: 1

Related Questions