Cheetah
Cheetah

Reputation: 14379

Logging and debug messages

I have my debug messages evaluate expensive string operations when printing messages like this:

Log.Debug("here it is" + obj.ExpensiveToString())

Now even if the log level isn't set to Debug, it still evaluates the expensive string operation.

So without having to do this:

if(debugMode) Log.Debug("here it is" + obj.ExpensiveToString())

or having lots of complex Log.Debug() methods, how can I get around this?

Upvotes: 0

Views: 605

Answers (1)

Sten Petrov
Sten Petrov

Reputation: 11040

use a compiler directive

#if DEBUG
  Log.Debug("Here it is: "+obj.ExpensiveToString());
#endif

since these directives increase code verbosity use them for the expensive parts.

Another alternative is to modify or supplement your log system to accept a Func<string>

public void LogDebug(Func<string> evalMe){

#if DEBUG
    if (evalMe!=null)
      Log.Debug(evalMe);
#endif

}

and then call it like this:

LogDebug(()=>"Here it is: "+obj.ExpensiveToString());

Upvotes: 3

Related Questions