Debug.WriteLine in release build

后端 未结 4 1186
[愿得一人]
[愿得一人] 2020-12-13 17:15

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

相关标签:
4条回答
  • 2020-12-13 17:24

    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

    0 讨论(0)
  • 2020-12-13 17:25

    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.

    0 讨论(0)
  • 2020-12-13 17:34

    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

    0 讨论(0)
  • 2020-12-13 17:41

    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 ); }
    }
    
    0 讨论(0)
提交回复
热议问题