When writing code, I often place debug messages in the code. The debug messages are handled by a logger class, which outputs the messages to file in debug mode and discards them in release modes.
It looks a little something like this:
class Logger : IDisposable
{
private StreamWriter m_Logger = null;
public void Start(string logFile)
{
m_Logger = new StreamWriter(logFile);
m_Logger.AutoFlush = true;
}
public void Dispose()
{
if (m_Logger != null) m_Logger.Dispose();
}
public void WriteLine(string message)
{
if (m_Logger != null) m_Logger.WriteLine(message);
}
}
An instance is created at startup, and is accessible from the Program class. I then check for debug like this:
#if DEBUG
Program.Log.Start("app.log");
#endif
This works great, in that it dumps debug info when in debug mode, and doesn’t in release mode. However, if I run the release executable through a utility such as strings, I can still see the debug strings. I’d prefer to keep them out of the release build entirely, to help prevent reverse engineering.
The only solution I’ve found so far is to wrap all debug messages in preprocessor conditionals:
// < some code here >
#if DEBUG
Program.Log.WriteLine("Some debug message.");
#endif
// < more code here >
This is pretty tedious and ugly. My first thought was to use some sort of preprocessor macro, but C# doesn’t support them. Is there a more elegant solution than the one I’m using right now?
To avoid using #if-#endif on each WriteLine call, try using ConditionalAttribute on the logger method itself:
This will be excluded from MSIL in case of a Release build.