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

在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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值