Enabling ATLTRACE output in Release configuration builds

The original intent is pretty clear, as MSDN states:

In release builds, ATLTRACE2 compiles to (void) 0.

As simple as this, but once in a while you are in a situation where release build fails to work for unknown reason and you need additional information for troubleshooting, and then you remember that you had debug tracing code still nicely available in the source, it is just being stripped out by definition of ATLTRACE/ATLTRACE2 macros for release builds.

To avoid reinvention of the wheel and putting new tracing, it might make sense to just re-enable existing tracing (certainly, if putting debug build binary is out of question, which might be the case in production environment and/or to avoid the hassle of installing additional runtime).

The macros need to be #undef’ined and redefined appropriately with or without limiting scope by push_macro/pop_macro #pragma’s. The trick with macro has to reach two goals, to pick file name, line and current symbol name using __FILE__ and friend macros, and also accept variable number of arguments.

The trick ATL does and we can use too is to define a helper class, with constructor taking file name, line and symbol name values, and cast operator () taking actual tracing parameters and arguments. Internally the output can be mapped to OutputDebugString API so that output could be seen using external tool such as DebugView.

When everything is well set, new the macros in question can be defined as follows:

#pragma push_macro("ATLTRACE")
#pragma push_macro("ATLTRACE2")

#undef ATLTRACE
#undef ATLTRACE2

#define ATLTRACE2 CAtlTrace(__FILE__, __LINE__, __FUNCTION__)
#define ATLTRACE ATLTRACE2

int _tmain(int argc, _TCHAR* argv[])
{
    ATLTRACE("First: %d\n", __LINE__);
    ATLTRACE(L"Second: %d\n", __LINE__);
    ATLTRACE2(atlTraceGeneral, 2, "Third: %d\n", __LINE__);
    ATLTRACE2(atlTraceGeneral, 2, L"Fourth: %d\n", __LINE__);
    return 0;
}

#pragma pop_macro("ATLTRACE2")
#pragma pop_macro("ATLTRACE")

And the Release configuration output will be:

Visual C++ .NET 2010 source code is available from SVN; in particular CAtlTrace class is here.

Bonus reading:

Leave a Reply