dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.54k stars 25.3k forks source link

Message template should be compile time constant #25790

Closed ivog closed 2 years ago

ivog commented 2 years ago

In Chapter "Create Logs" the example uses this:

    Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
    _logger.LogInformation(Message);

It would be better if the example would use:

    string messageTemplate = "About page visited at {PageVisitDate}";
    _logger.LogInformation(messageTemplate, DateTime.UtcNow.ToLongTimeString());

This allows structured logging. The logger can save the parametervalues separately from the template which allows for easier searching in application insights or other sinks.

See also this anwer on stackoverflow


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

fiyazbinhasan commented 2 years ago

Agreed! From the StackOverflow answer

Now for the real question: Why is there a warning? The answer is that string interpolation prevents structured logging. When you pass the variables after the message, you make it possible for the logger to save them separately. If you just save the log to a file you may not see a difference, but if you later decide to log to a database or in some JSON format, you can just change your logging sink and you will be able to search through the logs much easier without changing all the log statements in your code.

Though I've been facing this warning lately in Rider only. But I agree that it's a best practice that we emphasize using templates rather than string interpolation. And what a better way to show it off in this very logging documentation. What do you guys think?

guardrex commented 2 years ago

Thanks ... I've got a sec to fix it up.