本文介绍了如何重定向 qDebug、qWarning、qCritical 等输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调试输出中使用了很多 qDebug() << 语句.是否有任何跨平台的方式可以将调试输出重定向到文件,而无需求助于 shell 脚本?我猜 open()dup2() 将在 Linux 中完成这项工作,但它会在 Windows 中使用 MinGW 编译的工作?

I'm using a lot of qDebug() << statements for debug output. Is there any cross-platform way I can redirect that debug output to a file, without resorting to shell scripts? I'm guessing that open() and dup2() will do the job in Linux, but will it work compiled with MinGW in Windows?

也许有一种 Qt 方法可以做到这一点?

And maybe there is a Qt way to do it?

推荐答案

您必须使用 qInstallMsgHandler 函数安装消息处理程序,然后,您可以使用 QTextStream调试消息写入文件.这是一个示例示例:

You've to install a message handler using qInstallMsgHandler function, and then, you can use QTextStream to write the debug message to a file. Here is a sample example:

#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)
", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)
", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)
", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)
", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)
", localMsg.constData(), context.file, context.line, context.function);
        abort();
    }
}

int main(int argc, char **argv)
{
    qInstallMessageHandler(myMessageOutput); // Install the handler
    QApplication app(argc, argv);
    ...
    return app.exec();
}

取自 qInstallMsgHandler 的文档(我只添加了注释):

Taken from the doc of qInstallMsgHandler (I only added the comments):

在上面的例子中,函数 myMessageOutput 使用了 stderr,你可能想用其他文件流替换它,或者完全重写函数!

In the above example, the function myMessageOutput uses stderr which you might want to replace with some other file stream, or completely re-write the function!

一旦你编写并安装了这个函数,你所有的 qDebug(以及 qWarningqCritical 等)消息将被重定向到您正在处理程序中写入的文件.

Once you write and install this function, all your qDebug (as well as qWarning, qCritical etc) messages would be redirected to the file you're writing to in the handler.

这篇关于如何重定向 qDebug、qWarning、qCritical 等输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 23:51