Debug.WriteLine in release build
Solution 1:
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:
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:
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:
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