您的位置:首页 > 编程语言 > Qt开发

qt 调试语句的处理 禁用和重定向到文件

2015-05-21 13:51 309 查看
转载自:http://blog.csdn.net/godvmxi/article/details/41774815, 感谢原作者分享!

在qt调试中,qdebug是个非常方便的功能,只需要在包含#include<QDebug> ,你便可以在代码中随时随地使用打印调试语句了,并且可以选择对应的调试等级。

这些函数按照调试的等级以此有,其中qFatal执行后程序直接退出,并用对话框提示相关错误:

qDebug /

qWarning /

qCritical

qFatal

这些函数的使用用法如下:

#include<QDebug>
int main(int argc, char *argv[])
{
qDebug()<<"hello qDebug";
qWarning()<<"hello qWarning";
qCritical()<<"hello qCritical";
//    qFatal()   <<"hello qFatal"; //can use like this
qFatal("hello qFatal"); // will exit the program
}


但是当程序完成的时候,就需要根据需求关闭或者重定向到所需的文件作为log了


1:禁用qDebug输出

在工程的.pro文件里加上以下编译批令即可:

DEFINES += QT_NO_DEBUG_OUTPUT

有些人说在文件中增加该宏定义即可,我测试了一下,不管用的。


2:重定向到指定文件,并设置log level

#include <QtDebug>
#include <QFile>
#include <QTextStream>

void customMessageHandler(QtMsgType type, const char *msg)
{
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;

case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
abort();
}

QFile outFile("debuglog.txt");
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << txt << endl;
}

int main( int argc, char * argv[] )
{
QApplication app( argc, argv );

//Lets register our custom handler, before we start
qInstallMsgHandler(customMessageHandler);
...
return app.exec();
}



3: 简述一下qdebug()的等级

参看qt源代码可以发现,使用QT_NO_DEBUG_STREAM便可以禁用debug,waring,critical信息,但是不会禁用fatal信息,这个需要注意一下。

#ifndef QT_NO_DEBUG_STREAM
QDebug debug() const;
QDebug debug(const QLoggingCategory &cat) const;
QDebug debug(CategoryFunction catFunc) const;
QDebug warning() const;
QDebug warning(const QLoggingCategory &cat) const;
QDebug warning(CategoryFunction catFunc) const;
QDebug critical() const;
QDebug critical(const QLoggingCategory &cat) const;
QDebug critical(CategoryFunction catFunc) const;

QNoDebug noDebug() const Q_DECL_NOTHROW;
#endif // QT_NO_DEBUG_STREAM
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: