Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Message template should be compile time constant

I have this code

[HttpGet("average/{videoGuid}")]
public async Task<IActionResult> AverageRatingOfVideo([FromRoute] string videoGuid)
{
    _logger.LogInformation($"Finding average rating of video : {videoGuid}");
    var avg = await _ratingService.GetVideoRatingAverageAsync(videoGuid);
    return Ok(avg);
}

and I'm getting a warning here $"Finding average rating of video : {videoGuid}"

Message template should be compile time constant

I'm using Rider, there is no suggestion to fix this warning.

I can't understand why this gives me a warning, how could I fix this ?

like image 615
Ali Faris Avatar asked Jan 24 '21 19:01

Ali Faris


1 Answers

The way to get rid of the warning is to supply the variable videoGuid separately, like this:

_logger.LogInformation("Finding average rating of video : {VideoGuid}", videoGuid);

Here, I first removed the $ sign, thereby turning off the string interpolation performed by C#. The {videoGuid} in the string now becomes a "property" instead, and so I pass the variable as a second argument to LogInformation. Rider also complains that properties in strings should start with a capital letter, so I changed it to {VideoGuid}.

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.

There's a good discussion of this over on Software Engineering Stack Exchange.

like image 58
Rolf Staflin Avatar answered Nov 18 '22 17:11

Rolf Staflin