All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S6675.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

The Trace.WriteLineIf Method from the System.Diagnostic.Trace facility writes a trace if the condition passed as the first parameter is true.

TraceSwitch allows trace control via bool properties for each relevant TraceLevel, such as TraceSwitch.TraceError.

Using Trace.WriteLineIf with such properties should be avoided since it can lead to misinterpretation and produce confusion.

In particular, Trace.WriteLineIf may appear as equivalent to the level-specific tracing methods provided by Trace, such as Trace.Error, but it is not.

The difference is that Trace.WriteLineIf(switch.TraceError, …​) conditionally writes the trace, based on the switch, whereas Trace.TraceError always writes the trace, no matter whether switch.TraceError is true or false.

Moreover, unlike Trace.TraceError, Trace.WriteLineIf(switch.TraceError, …​) would behave like Trace.WriteLine(…​) when switch.TraceError is true, writing unfiltered to the underlying trace listeners and not categorizing the log entry by level, as described more in detail in {rule:csharpsquid:S6670}.

How to fix it

The fix depends on the intent behind the use of TraceSwitch levels with Trace.WriteLineIf.

If it is trace categorization, level-specific tracing methods, such as Trace.TraceError or Trace.TraceWarning, should be used instead.

If it is trace filtering, TraceSource should be used instead.

If it is log filtering, Trace should be replaced by logging APIs, such as the ILogger API.

Modern logging APIs are also more suitable than Trace when high-performance logging is required.

Resources

Documentation

Articles & blog posts





© 2015 - 2024 Weber Informatics LLC | Privacy Policy