Runtime: Debug.WriteLine does not write to Trace.Listeners

Created on 2 Mar 2017  路  9Comments  路  Source: dotnet/runtime

In net45, calling Debug.WriteLine would pass the message to the Trace.Listeners collection. But in corefx, that doesn't happen.

The following program can be compiled for net45 or netcoreapp1.0 (with the System.Diagnostics.TraceSource package installed):

using System;
using System.Diagnostics;

namespace ConsoleApp41
{
    class Program
    {
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new MyListener());
            Trace.WriteLine("Traced message");
            Debug.WriteLine("Debug message");
        }

        private class MyListener : TraceListener
        {
            public MyListener()
            {
            }

            public override void Write(string message)
            {
                Console.WriteLine("Our listener got: " + message);
            }

            public override void WriteLine(string message)
            {
                Console.WriteLine("Our listener got: " + message);
            }
        }
    }
}

When run on .NET Framework, the output is:

Our listener got: Traced message
Our listener got: Debug message

For dotnet run the output is merely:

Our listener got: Traced message
area-System.Diagnostics.Tracing bug

Most helpful comment

This was addressed for .NET Core 3.0.

All 9 comments

This breaks some of our unit tests when we run them on CoreCLR because we use TraceListeners to verify that our product code invokes Debug.Assert.

cc: @weshaggard

Desktop parity = milestone 2.0

This is an intentional break in behavior because the Debug class is at a much lower level then TraceSource which is a higher level concept in .NET Core.

@AArnott Is it just your tests that are hitting the issue or is there a larger impact for your tracing?

It's just tests. No shipping scenario depends on this for me.

@AArnott thanks. I'm inclined to still keep this change in behavior to avoid pulling in all the Trace infrastructure into the core where Debug is implemented. If we find we need to support this for a real scenario then we can entertain trying to dynamically hook these up to one another, but I would only do that if we feel it is a critical scenario we need to support.

@weshaggard : How do we listen to Debug.WriteLine() currently, as Trace.Listeners is not listening to Debug logs?

@jayaranigarg there isn't a direct way to do it. Note that Debug.WriteLine calls only exist in debug code and thus will not be anywhere in release code anyway. Debug.WriteLine only writes to the debugger output, see https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Diagnostics/Debug.Windows.cs#L51.

This was addressed for .NET Core 3.0.

Was this page helpful?
0 / 5 - 0 ratings