Loupe - Log - Monitor - Resolve
Loupe / Developer's Guide / For .NET Core / 6 / 8 / Logging / Using with Other Log Systems / Using Microsoft.Extensions.Logging with Loupe / Developer's Reference - Microsoft.Extensions.Logging Message Formatting
In This Topic
    Developer's Reference - Microsoft.Extensions.Logging Message Formatting
    In This Topic

    Microsoft.Extensions.Logging supports multiple ways of specifying a message template and then populating that template with values when the log message is recorded.  You can use traditional string.Format approaches, string interpolation, and Semantic Logging.

     Preferred Approach: Semantic Logging

    The preferred approach is to use a Semantic Logging approach where you specify a label for the data being inserted and the values are replaced in order.  In this case we don't use the $ to designate an interpolated string but instead rely on the logging framework to calculate the substitutions.

    logger.LogInformation("This message will have three formatted values " +
                          "inserted as semantic logging: " +
                          "{First}, {Second:N0}, {Third:g}", firstVal, secondVal, thirdVal);
    

    However, instead of using labels aligned with the variable name, use consistent labels for what the data is, like this:

    logger.LogInformation("This message will have three formatted values " +
                          "inserted as semantic logging: " +
                          "{Order}, {OrderQuantity:N0}, {OrderTimestamp:g}",
        firstVal, secondVal, thirdVal);
    

    If you consistently use the label Order when referring to the order Id (regardless of what the value is called in your code) you can then search log messages for that Order value and find all related messages.

     Interpolated Strings

    .NET supports string interpolation where the compiler will translate variable names at compile time into the relevant insertion point. This is done by prefixing the string literal with $ then using the name of a variable or property in the current execution context within the template.  This is resolved at compile time, making it easier to develop and maintain than the historical ordinal-based method of string.Format. 

    For more information on how to use string interpolation, see the official documentation on interpolated strings.

    Compared to Semantic Logging this does have a minor performance change where the insertions will always be done, even if the message is ultimately not logged.  

    var firstVal = "first";
    var secondVal = 2000;
    var thirdVal = DateTimeOffset.UtcNow;
    logger.LogInformation("This message will have three formatted values " +
        "inserted with string interpolation: " +
        $"{firstVal}, {secondVal:N0}, {thirdVal:g}");
    

     

    See Also