Where can I see ATLTRACE output? - c++

I'm maintaining a C++ COM project. There are some trace lines like ATLTRACE(message);
I searched ATLTRACE. MSDN told Visual C++ output window will display it. However, the product is a release one. The customer won't have the source nor to debug it in VS. So is there any other convenient way to see it? Will Windows Event viewer catch that? Or I have to change the code? Win7, VS2013

The ATLTRACE only uses only the debug output and it works only in the Debug version!
So you may give the enduser a debug version for testing purpose, and use DebugView from Sysinternals. But this may be complicated because you also have to over the debug runtimes that are not redistributable.
But you can easily write your own MY_TRACE macro that has the same functionality.
#define MY_TRACE GetMyTracer() // returns object of CMyTracer
...
class CMyTracer
{
...
// Helper operator to get the trace commands. They call the TraceV functions
void operator()(PCSTR pszFormat, ...);
void operator()(PCWSTR pszFormat, ...);
// Worker functions that do the real job calling TraceV functions
void Trace(PCSTR pszFormat, ...);
void Trace(PCWSTR pszFormat, ...);
// Allowed to be virtual to do some internal mystique stuff, like redirecting and this functions perform all output...
virtual void TraceV(PCSTR pszFormat, va_list args);
virtual void TraceV(PCWSTR pszFormat, va_list args);
...
Now you can use this instead of ATLTRACE
...
MYTRACE("Simple output\n");
MYTRACE("More complex output %d\n", 4711);
Note: It is not wise to replace all ATLTRACE macros with your own replacement. You may spread your trace output onto locations were it don't have impact un speed, but is worth the information.

ATLTRACE is a macro that compiles to nothing in a release build. You'll need to rebuild the project with the _DEBUG macro defined (see <atltrace.h>) to get those to display. However, output generated by ATLTRACE is a debug output string, and will typically only display in the debugger's output window.
If there is important information you need, and if it is in code you control, you'll be better off changing the ATLTRACE macro usage to something else, to either log to the event log or a log file the customer can send to you.

As mentioned by 1201ProgramAlarm, release builds of ATL projects have ATLTRACE macros evaluated to nothing and the binary has no real code generated for respective source code lines. That is, you cannot see the output without altering source code.
In order to not alter the project much, you can redefine the tracing macro itself and produce release build with tracing capabilities where output is routed as defined by you, for example to standard debug output using OutputDebugString API.
See:
How to enable the TRACE macro in Release mode?
AtlReleaseTrace

Related

Qt SIGABRT alternative message?

I'm using Qt5.9, a simple check:
assert(pobjNode != NULL);
Will cause the Qt Signal Received error dialog to be displayed which doesn't give any helpful information about where the problem is or what it is.
Is there a way to replace this useless information with something a bit more helpful?
What I'm thinking of is a way to set-up the dialog to display what could be an error in the event of an error.
Q_ASSERT is a custom assert macro which supposedly enhances the standard assert function.
The error message is handled by qFatal(), which can behave slightly better on some platforms than the standard assert macro. For example on Windows it will trigger the Visual Studio debugger at the point where the assertion fails instead of just calling abort().
You can also redirect the output of Qt error message functions such as qFatalto your custom message handler ( with qInstallMessageHandler() ). It can be useful for example if you want to redirect the errors message to a file.
Also note that Q_ASSERT is disabled with the macro QT_NO_DEBUG(while assert is disabled by NDEBUG) : this can be used to separate your asserts between Qt-related code and the rest.
Q_ASSERT_X Prints the message what together with the location where, the source file name and line number if test is false.
Prints the message what together with the location where, the source file name and line number if test is false.
Example:
// File: div.cpp
#include <QtGlobal>
int divide(int a, int b)
{
Q_ASSERT_X(b != 0, "divide", "division by zero");
return a / b;
}
to read more on test and debug.
You might define your own MY_ASSERT macro. On Linux it could even call another function which uses Glibc backtrace functions or Ian Taylor's libbacktrace library (provided your code is compiled with DWARF debug information using g++ -g) and perhaps display such information in a modal dialog, or on stderr. However, it should probably not return. Read also about Qt and Unix signals and signal-safety(7).
But assert detects a bug which you should correct. Try hard to avoid shipping code with such programmer bugs.
On Linux, the usual assert -it is a macro defined in /usr/include/assert.h- will call on failure __assert_fail (in your C library, but you might redefine it yourself) which would indirectly call abort which indirectly makes a core dump which you can inspect post-mortem using the gdb debugger. You only need to enable core dumps (using ulimit -c builtin in your bash terminal).

Fastest way to make console output "verbose" or not

I am making a small system and I want to be able to toggle "verbose" text output in the whole system.
I have made a file called globals.h:
namespace REBr{
extern bool console_verbose = false;
}
If this is true I want all my classes to print a message to the console when they are constructing, destructing, copying or doing pretty much anything.
For example:
window(string title="",int width=1280,int height=720):
Width(width),Height(height),title(title)
{
if(console_verbose){
std::cout<<"Generating window #"<<this->instanceCounter;
std::cout<<"-";
}
this->window=SDL_CreateWindow(title.c_str(),0,0,width,height,SDL_WINDOW_OPENGL);
if(console_verbose)
std::cout<<"-";
if(this->window)
{
this->glcontext = SDL_GL_CreateContext(window);
if(console_verbose)
std::cout<<".";
if(this->glcontext==NULL)
{
std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_OPENGLCONTEXT: "<<SDL_GetError()<<std::endl;
}
}
else std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_WINDOW: "<<SDL_GetError()<<std::endl;
if(console_verbose)
std::cout<<">done!"<<endl;
}
Now as you can see I have a lot of ifs in that constructor. And I REALLY dont want that since that will slow down my application. I need this to be as fast as possible without removing the "loading bar" (this helps me determine at which function the program stopped functioning).
What is the best/fastest way to accomplish this?
Everying in my system is under the namespace REBr
Some variants to achieve that:
Use some logger library. It is the best option as it gives you maximum flexibility and some useful experience ;) And you haven't to devise something. For example, look at Google GLOG.
Define some macro, allowing you to turn on/off all these logs by changing only the macro. But it isn't so easy to write such marco correctly.
Mark your conditional flag as constexpr. That way you may switch the flag and, depending on its value, compiler will optimise ifs in compiled program. But ifs will still be in code, so it looks kinda bulky.
Anyway, all these options require program recompilation. W/o recompilation it is impossible to achieve the maximum speed.
I often use a Logger class that supports debug levels. A call might look like:
logger->Log(debugLevel, "%s %s %d %d", timestamp, msg, value1, value2);
The Logger class supports multiple debug levels so that I can fine tune the debug output. This can be set at any time through the command line or with a debugger. The Log statement uses a variable length argument list much like printf.
Google's logging module is widely used in the industry and supports logging levels that you can set from the command line. For example (taken from their documentation)
VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
VLOG(2) << "I'm printed when you run the program with --v=2 or higher";
You can find the code here https://github.com/google/glog and the documentation in the doc/ folder.

(Define a macro to) facilitate OpenGL command debugging?

Sometimes it takes a long time of inserting conditional prints and checks to glGetError() to narrow down using a form of binary search where the first function call is that an error is first reported by OpenGL.
I think it would be cool if there is a way to build a macro which I can wrap around all GL calls which may fail which will conditionally call glGetError immediately after. When compiling for a special target I can have it check glGetError with a very high granularity, while compiling for typical release or debug this wouldn't get enabled (I'd check it only once a frame).
Does this make sense to do? Searching for this a bit I find a few people recommending calling glGetError after every non-draw gl-call which is basically the same thing I'm describing.
So in this case is there anything clever that I can do (context: I am using GLEW) to simplify the process of instrumenting my gl calls this way? It would be a significant amount of work at this point to convert my code to wrap a macro around each OpenGL function call. What would be great is if I can do something clever and get all of this going without manually determining which are the sections of code to instrument (though that also has potential advantages... but not really. I really don't care about performance by the time I'm debugging the source of an error).
Try this:
void CheckOpenGLError(const char* stmt, const char* fname, int line)
{
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
printf("OpenGL error %08x, at %s:%i - for %s\n", err, fname, line, stmt);
abort();
}
}
#ifdef _DEBUG
#define GL_CHECK(stmt) do { \
stmt; \
CheckOpenGLError(#stmt, __FILE__, __LINE__); \
} while (0)
#else
#define GL_CHECK(stmt) stmt
#endif
Use it like this:
GL_CHECK( glBindTexture2D(GL_TEXTURE_2D, id) );
If OpenGL function returns variable, then remember to declare it outside of GL_CHECK:
const char* vendor;
GL_CHECK( vendor = glGetString(GL_VENDOR) );
This way you'll have debug checking if _DEBUG preprocessor symbol is defined, but in "Release" build you'll have just the raw OpenGL calls.
BuGLe sounds like it will do what you want:
Dump a textual log of all GL calls made.
Take a screenshot or capture a video.
Call glGetError after each call to check for errors, and wrap glGetError so that this checking is transparent to your program.
Capture and display statistics (such as frame rate)
Force a wireframe mode
Recover a backtrace from segmentation faults inside the driver, even if the driver is compiled without symbols.

how to get function name and line number when project crashed in release mode

i have a project in C++/MFC
when i run its in debug mode and project crashed
i can get function and line number of code
with SetUnhandledExceptionFilter function
but in release mode i can not get it
i am test this function and source
_set_invalid_parameter_handler msdn.microsoft.com/en-us/library/a9yf33zb(v=vs.80).aspx
StackWalker http://www.codeproject.com/KB/threads/StackWalker.aspx
MiniDumpReader & crashrpt http://code.google.com/p/crashrpt/
StackTracer www.codeproject.com/KB/exception/StackTracer.aspx
any way to get function and line of code when project crashed in release mode
without require pdb file or map file or source file ?
PDB files are meant to provide you this information; the flaw is that don't you want a PDB file. I can understand not wanting to release the PDB to end users, but in that case why would you want them to see stack trace information? To me your goal is conflicting with itself.
The best solution for gathering debug info from end users is via a minidump, not by piecing together a stack trace on the client.
So, you have a few options:
Work with minidumps (ideal, and quite common)
Release the PDBs (which won't contain much more info than you're already trying to deduce)
Use inline trace information in your app such as __LINE__, __FILE__, and __FUNCTION__.
Just capture the crash address if you can't piece together a meaningful stack trace.
Hope this helps!
You can get verbose output from the linker that will show you where each function is placed in the executable. Then you can use the offset from the crash report to figure out which function was executing.
In release mode, this sort of debugging information isn't included in the binary. You can't use debugging information which simply isn't there.
If you need to debug release-mode code, start manually tracing execution by writing to a log file or stdout. You can include information about where your code appears using __FUNCTION__ and __LINE__, which the compiler will replace with the function/line they appear in/on. There are many other useful predefined macros which you can use to debug your code.
Here's a very basic TR macro, which you can sprinkle through out your code to follow the flow of execution.
void trace_function(const char* function, int line) {
std::cout << "In " << function << " on line " << line << std::endl;
}
#define TR trace_function(__FUNCTION__, __LINE__)
Use it by placing TR at the top of each function or anywhere you want to be sure the flow of execution is reaching:
void my_function() {
TR();
// your code here
}
The best solution though, is to do your debugging in debug mode.
You can separate the debug symbols so that your release version is clean, then bring them together with the core dump to diagnose the problem afterwards.
This works well for GNU/Linux, not sure what the Microsoft equivalent is. Someone mentioned PDB...?

Is there a TRACE statement for basic win32 C++?

In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?
_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873
From the msdn docs, Macros for Reporting:
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.
There is also OutputDebugString. However that will not be removed when compiling release.
Trace macros that provide messages with source code link, run-time callstack information, and function prototype information with parameter values:
Extended Trace: Trace macros for Win32
I just use something like this (from memory, not tested at all...)
#define TRACE(msg) {\
std::ostringstream ss; \
ss << msg << "\n"; \
OutputDebugString(msg.str()); \
}
And then I can write things like :-
TRACE("MyClass::MyFunction returned " << value << " with data=" << some.data);
You can wrap that in some #ifdefs to remove it in release builds easily enough.
I found that using the _RPT() macro will also work with a C source file in Visual Studio 2005. This article Debugging with Visual Studio 2005/2008: Logging and Tracing provides an overview of TRACE, _RPT, and other logging type macros.
I generate a line for a log file called the ASSRTLOG which contains logs and when writing the log to the file, I also do the following source code line:
_RPT1(_CRT_WARN, "ASSRTLOG: %s", szLog1);
This line puts the same log that is going into the log file into the output window of the Visual Studio 2005 IDE.
You might be interested in the mechanics behind the approach we are using for logging. We have a function PifLogAbort() which accepts a series of arguments that are then used to generate a log. These arguments include the name of the file where the log is being generated along with the line number. The macro looks like this:
#define NHPOS_ASSERT_TEXT(x, txt) if (!(x)) { PifLogAbort( (UCHAR *) #x , (UCHAR *) __FILE__ , (UCHAR *) txt , __LINE__ );}
and the function prototype for PifLogAbort() look like this:
PifLogNoAbort(UCHAR *lpCondition, UCHAR *lpFilename, UCHAR *lpFunctionname, ULONG ulLineNo)
and to use the macro we will insert a line like this:
NHPOS_ASSERT_TEXT(sBRetCode >= 0, "CliEtkTimeIn(): EtkTimeIn() returned error");
What this macro will do is that if the return code is less than 0 (the assertion fails), a log will be generated with the provided text. The log includes the condition that generated the log along with file name and line number.
The function PifLogAbort() generates logs with a specified length and treats the output file as a circular buffer. The logs have a time and date stamp as well.
In those cases where we want to generate the descriptive text dynamically at run time, perhaps to provide the actual error code value, we use the sprintf() function with a buffer as in the following code sequence:
if (sErrorSave != STUB_BM_DOWN) {
char xBuff[128];
sprintf(xBuff, "CstSendBMasterFH: CstComReadStatus() - 0x%x, sError = %d", usCstComReadStatus, CliMsg.sError);
NHPOS_ASSERT_TEXT((sErrorSave == STUB_BM_DOWN), xBuff);
}
If we want the logs to not be generated, all we need to do is to go to the single header file where the macro is defined and define it to be nothing then recompile. However we have found that these logs can be very valuable when investigating field issues and are especially useful during integration testing.
Windows Events are a potential replacement for TRACE macros, depending on your particular scenario. The code gets compiled into both Debug and Release configurations. Event tracing can then be dynamically enabled and disabled, displayed in real-time, or dumped on a client's machine for later diagnosis. The traces can be correlated with trace information gathered from other parts of the OS as well.
If you merely need to dump information whenever code reaches certain checkpoints, together with variable content, stack traces, or caller names, Visual Studio's Tracepoints are a non-intrusive option to do so.