
* S6674: add how to fix section * S6677: add how to fix section * S2629: add how to fix section * S6670: add how to fix section * S1312: add how to fix section * S6672: add how to fix section * S6670: add compliant/noncompliant headers * S6669: add how to fix section * S6668: add how to fix section * S2629: remove method definition * S6669: update formatting * S6670: add links * Fix formatting
41 lines
2.0 KiB
Plaintext
41 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Logging arguments should not require evaluation in order to avoid unnecessary performance overhead. When passing concatenated strings or string interpolations directly into a logging method, the evaluation of these expressions occurs every time the logging method is called, regardless of the log level. This can lead to inefficient code execution and increased resource consumption.
|
|
|
|
Instead, it is recommended to use the overload of the logger that accepts a log format and its arguments as separate parameters. By separating the log format from the arguments, the evaluation of expressions can be deferred until it is necessary, based on the log level. This approach improves performance by reducing unnecessary evaluations and ensures that logging statements are only evaluated when needed.
|
|
|
|
Furthermore, using a constant log format enhances observability and facilitates searchability in log aggregation and monitoring software.
|
|
|
|
The rule covers the following logging frameworks:
|
|
|
|
* https://www.nuget.org/packages/Microsoft.Extensions.Logging[Microsoft.Extensions.Logging]
|
|
* https://www.nuget.org/packages/Castle.Core[Castle.Core]
|
|
* https://www.nuget.org/packages/log4net[log4net]
|
|
* https://www.nuget.org/packages/Serilog[Serilog]
|
|
* https://www.nuget.org/packages/NLog[Nlog]
|
|
|
|
== How to fix it
|
|
|
|
Use an overload that takes the log format and the parameters as separate arguments. The log format should be a constant string.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
logger.DebugFormat($"The value of the parameter is: {parameter}.");
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
logger.DebugFormat("The value of the parameter is: {Parameter}.", parameter);
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.interpolatedstringhandlerattribute[InterpolatedStringHandlerArgumentAttribute] |