qdebug重定向_如何重定向qDebug,qWarning,qCritical等输出?

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?

And maybe there is a Qt way to do it?

解决方案

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

#include

#include

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)\n", localMsg.constData(), context.file, context.line, context.function);

break;

case QtInfoMsg:

fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);

break;

case QtWarningMsg:

fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);

break;

case QtCriticalMsg:

fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);

break;

case QtFatalMsg:

fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", 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();

}

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

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!

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值