'The logging message template should not vary between calls (CA2254) when only passing on variables

I understand the concept of this warning (similar to this question), but what is wrong with this code?

    private async Task LogWarningAsync(short? userCodeId, string message, params object[] args)
    {
        _logger.LogWarning(message, args);

        // Do something on the database...
    }

The warning:

CA2254

The logging message template should not vary between calls to 'LoggerExtensions.LogWarning(ILogger, string?, params object?[])'



Solution 1:[1]

Here is a discussion of other people experiencing similar issues regarding CA2254. Hopefull this will get addressed in future versions.

For the time being, my best solution is to ignore the warning.

    private async Task LogWarningToDatabaseAsync(short? userCodeId, string message, params object[] args)
    {
#pragma warning disable CA2254 // Template should be a static expression
        _logger.LogWarning(message, args);
#pragma warning restore CA2254 // Template should be a static expression

        // Do something on the database...
    }

The alternative is not very exciting.

    private async Task LogWarningToDatabaseAsync(short? userCodeId, string message, params object[] args)
    {
        // Move to parent.
        //_logger.LogWarning(message, args);

        // Do something on the database...
    }

    private async Task SampleAsync(short? userCodeId, string aaa, string bbb)
    {
        // I'm not happy about repeating the input message every time this gets called.
        _logger.LogWarning("My sample message with data {aaa} and more data {bbb}", aaa, bbb);
        await LogWarningToDatabaseAsync(userCodeId, "My sample message with data {aaa} and more data {bbb}", aaa, bbb);
    }

Solution 2:[2]

This is actually a relevant warning. When producing logs within your application, you should not include variables to construct your log message. For example, "User 128973 logged in" is not a good log because you will not be able to group all of these "logged in" logs together to produce stats. Instead, you should put the userid in a separate object in your log object (additional data)

Solution 3:[3]

You really shouldn't suppress this analysis rule here, it's correct in your case to flag. Your use case scenario of wanting to log both to a DB table and to a log file should not be resolved by wrapping the regular logging system. It should be resolved by adding a logging output to your logger which logs to the table in question. Yes, it can be filtering and not log everything. Look up how to best do it with your logging library of choice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yoann Diguet
Solution 3 Philip Borgström