I want to add logging or tracing to my C# application but I don't want the overhead of formatting the string or calculating values to be logged if the log verbosity level is set so low that the message will not be logged.
In C++, you can use the preprocessor to define macros that will prevent code from being executed at all like this:
#define VLOG(level,expr) if (level >= g_log.verbosity) { g_log.output << expr; }
Used like this:
VLOG(5,"Expensive function call returns " << ExpensiveFunctionCall());
How do you do that in C#?
I've read the Microsoft docs explaining the Trace and Debug facilities here, and they claim that using #undef DEBUG and #undef TRACE removes all tracing and debugging code from the produced executable, but does it really remove the whole call? Meaning, if I write
System.Diagnostics.Trace.WriteLineIf(g_log.verbosity>=5,ExpensiveFunctionCall());
it won't call my expensive function if I undefine TRACE? Or does make the call, then decide it won't trace anything?
Anyway, even if it does remove it, this is inferior to the C++ macro because I can't make that big ugly call look like my simple VLOG() call in C++ and still avoid evaluating parameters, can I? Nor can I avoid the overhead by defining the verbosity lower at runtime like I can in C++, right?