开发者

Compilter Directives - Suggestion - Run code in Debug mode only

I need to Log messages only when application is running in debug mode. I have found 2 ways:

First: Need to write 3 lines everywhere when logging is needed. But, Logger statement is disabled at compile time only which is exactly I need. Logger.Log will not be executed at all.

#if DEV_ENV
        Logger.Log("Application started !"); // This line is grayed. Perfect !
#endif

public static void Log(string message)
{
    Debug.WriteLine(message);
}

Second: Very neat. Only 开发者_开发知识库one line of code wherever logging is required. Not sure, whether Logger.Log statement is executed or not. If function call is removed at compile time only (same as first approach. But, now sure as line of code is not greyed out), I want to go with this.

Logger.Log("Application started !"); // This line is not grayed out. But, function is not called. So, confused whether its removed at compile time.

[Conditional("DEV_ENV")]
public static void Log(string message)
{
    Debug.WriteLine(message);
}

I am concerned about the performance differences.


From the MSDN page for the ConditionalAttribute:

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated with ConditionalAttribute is defined.

So, as it says, the method call is removed at compile time, same as the #if.


Depending on your compile settings, you could use:

if (System.Diagnostics.Debugger.IsAttached)
   Logger.Log("Application started !"); 

or,

#if DEBUG
    Logger.Log("Application started !"); 
#endif 


As George points out, the method call will not be compiled if the Conditional attribute is applied. This also means (as with removing the code directly using #If DEV_ENV) that any side effects included in the method call will also not occur - as always, the warning about having side effects in logging code are well founded:

public static void Main(String[] args)
{
    int i = 92;
    Log(string.Format("{0} became {1}", i++, i));
    Console.WriteLine(i);
    Console.ReadLine();
}

[Conditional("SKIP")]
private static void Log(string msg)
{
    Console.WriteLine(msg);
}

If SKIP is not defined, this code prints out 92. If SKIP is defined, it prints 92 became 93 and 93.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜