S6670 — "Trace.Write" and "Trace.WriteLine" should not be used

Language
C#
Type
Code smell
Severity
Minor
Tags
logging

Why is this an issue?

Trace.Write and Trace.WriteLine methods are writing to the underlying output stream directly, bypassing the trace formatting and filtering performed by TraceListener.TraceEvent implementations. It is preferred to use Trace.TraceError, Trace.TraceWarning, and Trace.TraceInformation methods instead because they call the TraceEvent method which filters the trace output according to the TraceEventType (Error, Warning or Information) and enhance the output with additional information.

How to fix it

Use the Trace.TraceError, Trace.TraceWarning, or Trace.TraceInformation methods.

Noncompliant code example


try
{
    var message = RetrieveMessage();
    Trace.Write($"Message received: {message}"); // Noncompliant
}
catch (Exception ex)
{
    Trace.WriteLine(ex); // Noncompliant
}

Compliant solution


try
{
    var message = RetrieveMessage();
    Trace.TraceInformation($"Message received: {message}");
}
catch (Exception ex)
{
    Trace.TraceError(ex);
}

Resources

Documentation

Articles & blog posts

↑ Back to top