Search code examples
c#string-formatting

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?


Solution

  • 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.)