I think it would be much cleaner to utilize partial methods to create your logging statements. That way you can log wherever you need it and can disable the code my omitting it the logging function definition. By using partial methods, if the definition is omitted, no IL is generated for the method and calls to the partial method are ignored as if it was never there.
Just mark the class partial
, define the signature of the partial method and call it like normal. Then wrap the actual implementation in the conditional compilation blocks.
partial class MyClass
{
// declare the partial method
static partial void Log(string format, params object[] arguments);
static void SomeMethod()
{
// call the log method like usual
Log("Source Site Set to: {0}", archiveQueueEntity.SourceSite);
Log("Source List Set to: {0}", archiveQueueEntity.SourceUrl);
Log("Destination Site Set to {0}", archiveQueueEntity.DestinationSite);
Log("Destination List Set to: {0}", archiveQueueEntity.DestinationUrl);
}
#if DEBUG
static partial void Log(string format, params object[] arguments)
{
Console.WriteLine(format, arguments);
}
#endif
}
Otherwise if you're not able to change it, you should still create a separate logging method and disable to actual printing in the method there. That way your method is called but does nothing.
static void Log(string format, params object[] arguments)
{
#if DEBUG
Console.WriteLine(format, arguments);
#endif
}
Or alternatively, use the Trace
class to do your logging. As long as you have no listeners registered, you will not see any of the logging messages. When debugging, add a ConsoleTraceListener
to the Listeners
collection.
#if DEBUG
Trace.Listeners.Add(new ConsoleTraceListener());
#endif
Trace.WriteLine("Source Site Set to: {0}", archiveQueueEntity.SourceSite);
Trace.WriteLine("Source List Set to: {0}", archiveQueueEntity.SourceUrl);
Trace.WriteLine("Destination Site Set to {0}", archiveQueueEntity.DestinationSite);
Trace.WriteLine("Destination List Set to: {0}", archiveQueueEntity.DestinationUrl);
Something that eluded me until now, use the ConditionalAttribute
attribute on the log function for both cases to achieve the same effect.
[Conditional("DEBUG")]
static void Log(string format, params object[] arguments)
{
Console.WriteLine(format, arguments);
}