Debug.WriteLine in release build

C#.NetDebugging

C# Problem Overview


Is there a way to use Debug.WriteLine in a release build without defining DEBUG?

C# Solutions


Solution 1 - C#

No, but you can use the Trace in release by defining TRACE and using Trace.WriteLine. Have a look here:

>https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c

Solution 2 - C#

No. If you don't define the DEBUG preprocessor symbol, any calls to Debug.* will be removed by the compiler due to the [Conditional("DEBUG")] attribute being applied.

You might want to consider Trace.WriteLine or other logging techniques though.

Solution 3 - C#

While you still have to define DEBUG - you don't have to do it assembly wide. You can define it only in the source files that you want. So if you want debug logging from a particular class you can define DEBUG just for that source file.

#define DEBUG
using System.Diagnostics;

...

class Logger
{
    void Log( string msg ){ Debug.WriteLine( msg ); }
}

Solution 4 - C#

Yes. You can, as mentioned in the above comments use TRACE, or without defining any compile time constants, by using Expression Trees.

        var p = Expression.Parameter(typeof(string), "text");
        var callExp =
            Expression.Call(
              typeof(System.Diagnostics.Debug).GetRuntimeMethod(
                   "WriteLine", new [] { typeof(string) }),
              p);
        Action<string> compiledAction = Expression.Lambda<Action<string>>(
                                         callExp, p)
                                         .Compile();

After this, you can invoke the Debug.WriteLine anytime, by calling

        compiledAction("Debug text");

You're essentially tricking the compiler by not having a static method call, but instead dynamically constructing it at run-time.

There is no performance-hit since, the action is compiled and re-used.

This is how I wrote a DebugLogger in SharpLog.

> You may take a look at the source code here, if it interests you: https://github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarstenView Question on Stackoverflow
Solution 1 - C#NickView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#Paul AlexanderView Answer on Stackoverflow
Solution 4 - C#user3513472View Answer on Stackoverflow