Karsten
Karsten

Reputation: 8144

Debug.WriteLine in release build

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

Upvotes: 73

Views: 28957

Answers (5)

Kaneko Qt
Kaneko Qt

Reputation: 115

Debugger.Log(0, null, "Your string here"); could be an alternative, it is used internally by Debug.Write and it also works in Release.

Upvotes: 1

Nick
Nick

Reputation: 25799

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

Upvotes: 63

user3513472
user3513472

Reputation:

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

Upvotes: 5

Paul Alexander
Paul Alexander

Reputation: 32367

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 ); }
}

Upvotes: 23

Jon Skeet
Jon Skeet

Reputation: 1500225

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.

Upvotes: 51

Related Questions