org.sonar.plugins.csharp.S6674.html Maven / Gradle / Ivy
A message template must conform to the specification. The rule raises an issue if the template string
violates the template string grammar.
Why is this an issue?
A message template needs to comply with a set of rules. Logging provider parse the template and enrich log entries with
the information found in the template. An unparsable message template leads to corrupted log entries and might result in a loss of information in the
logs.
The rule covers the following logging frameworks:
- Nuget package - Serilog
- Nuget package - Nlog
- Nuget package - Microsoft.Extensions.Logging
How to fix it
Follow the syntax described on https://messagetemplates.org/.
Code examples
Noncompliant code example
logger.LogError("Login failed for {User", user); // Noncompliant: Syntactically incorrect
logger.LogError("Login failed for {}", user); // Noncompliant: Empty placeholder
logger.LogError("Login failed for {User-Name}", user); // Noncompliant: Only letters, numbers, and underscore are allowed for placeholders
logger.LogDebug("Retry attempt {Cnt,r}", cnt); // Noncompliant: The alignment specifier must be numeric
logger.LogDebug("Retry attempt {Cnt:}", cnt); // Noncompliant: Empty format specifier is not allowed
Compliant solution
logger.LogError("Login failed for {User}", user);
logger.LogError("Login failed for {User}", user);
logger.LogError("Login failed for {User_Name}", user);
logger.LogDebug("Retry attempt {Cnt,-5}", cnt);
logger.LogDebug("Retry attempt {Cnt:000}", cnt);
Resources
Documentation
- Message Templates - Message template specification
- Microsoft Learn - Log message template
formatting
- NLog - How to use structured logging
- Serilog - Structured Data
- Serilog -
Serilog002
:
Message template syntax verifier
© 2015 - 2024 Weber Informatics LLC | Privacy Policy