Debug.WriteLine in release

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

+45
debugging c #
Mar 24 2018-11-12T00:
source share
4 answers

No, but you can use Trace in the release by specifying Trace and using Trace.WriteLine. . Look at here:

http://support.microsoft.com/kb/815788

+41
Mar 24 2018-11-11T00:
source share

No. If you do not specify a DEBUG preprocessor character, any calls to Debug.* Will be deleted by the compiler due to the [Conditional("DEBUG")] attribute used.

You might want to consider Trace.WriteLine or other logging methods.

+34
Mar 24 2018-11-11T00:
source share

While you still need to define DEBUG - you do not need to do this from the side. You can only define it in the source files you want. Therefore, if you want to keep a debug log from a specific class, you can define DEBUG only for this source file.

 #define DEBUG using System.Diagnostics; ... class Logger { void Log( string msg ){ Debug.WriteLine( msg ); } } 
+14
Apr 03 '12 at 6:12
source share

Yes. You can, as mentioned in the comments above, use TRACE with or without defining any compile-time constants 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 that, you can call Debug.WriteLine at any time by calling

  compiledAction("Debug text"); 

You essentially fool the compiler by not having a static method call, but instead dynamically creating it at run time.

No action has taken place since the failure, the action is compiled and reused.

This is how I wrote DebugLogger in SharpLog.

You can take a look at the source code here if you are interested: https://github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs

+3
May 15 '14 at 4:24
source share



All Articles