如何在MFC中重定向TRACE语句以减少来自AfxDumpStack()的数据流

How is it possible to redirect TRACE statements in MFC to reduce the data stream from AfxDumpStack()?

本文关键字:AfxDumpStack 数据流 MFC 重定向 语句 TRACE      更新时间:2023-10-16

我从AfxDumpStack看到可以重定向TRACE输出。

  • AFX_STACK_DUMP_TARGET_TRACE通过TRACE宏发送输出。TRACE宏仅在调试生成中生成输出;它在发布版本中不生成任何输出此外,TRACE可以重定向到除调试器之外的其他目标

斜体字是我的。

我从一个旧的应用程序用C++编程,希望使用只输出到TRACE或剪贴板的AfxDumpStack()转储部分堆栈。我只想输出其中的几行,所以我需要在输出之前处理字符串。

我该如何以最简单的方式完成这项工作?

编辑

这就是我的解决方案的代码:

class hook
{
public:
    hook()
    {
        VERIFY(_CrtSetReportHook2(_CRT_RPTHOOK_INSTALL, Hook) != -1);
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
        _CrtSetReportFile(_CRT_WARN, INVALID_HANDLE_VALUE);
    }
    ~hook()
    {
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
        VERIFY(_CrtSetReportHook2(_CRT_RPTHOOK_REMOVE, Hook) != -1);
    }
    static const size_t max_backtrace = 4;    // max calls to view
    static const size_t skip_stack_head = -5; // skips over calls related to AfxDumpStack()
    static size_t line;                       // current line being output from begin of stack dump
    static bool stack_out;                    // currently outputting stack dump
    static int Hook( int reportType, char *message, int *returnValue )
    {
        if (strcmp(message, "=== begin AfxDumpStack output ===rn") == 0)
        {
            stack_out = true;
            line = skip_stack_head;
        }
        else if (strcmp(message, "=== end AfxDumpStack() output ===rn") == 0)
        {
            OutputDebugString("rn");
            stack_out = false;
        }
        else
        {
            if (strcmp(message, "rn") == 0) // AfxStackDump() sends CRLF out on separate calls
            {
                if (!stack_out || line < max_backtrace-1)
                {
                    OutputDebugString("rnt");
                }
                ++line;
            }
            else if (!stack_out || line < max_backtrace)
            {
                OutputDebugString(message);
            }
        }
        return TRUE;
    }
};
size_t hook::line     = -1;
bool   hook::stack_out = false;
static hook junk;

唯一的问题是对AfxDumpStack()的调用需要生成一个线程。如果调用过多,这将影响应用程序的性能。

默认情况下,TRACE调用OutputDebugString

您可以使用DebugView,它捕获OutputDebugString输出,并可以选择将其记录到文件中。

除了更改应用程序(例如用_CrtSetReportHook2挂接输出)之外,似乎不可能直接将输出发送到文件。

在内部,MFC使用_CrtDbgReport来输出其TRACE消息。您可以调用_CrtSetReportMode来指定其输出的位置。完成此操作后,您可以调用_CrtSetReportFile来指定win32文件句柄(由CreateFile返回)。