问题描述
我在调试输出中使用了很多 qDebug() <<
语句.是否有任何跨平台的方式可以将调试输出重定向到文件,而无需求助于 shell 脚本?我猜 open() 和
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
(以及 qWarning
、qCritical
等)消息将被重定向到您正在处理程序中写入的文件.
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 等输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!