Qt 定制qDebug() 信息到log文件

Qt中有qInstallMsgHandler 方法可以去定制消息发生后的回调函数,它回调同时还有qDebug的级别信息。这样我们可以方便把错误消息定制到自己的log文件里面

如下:

Cpp代码   收藏代码
  1. #include <QtDebug>  
  2. #include <QFile>  
  3. #include <QTextStream>  
  4.  //回调函数实现debug信息到文件  
  5. void customMessageHandler(QtMsgType type, const char *msg)  
  6. {  
  7.     QString txt;  
  8.     switch (type) {  
  9.     case QtDebugMsg:  
  10.         txt = QString("Debug: %1").arg(msg);  
  11.         break;  
  12.    
  13.     case QtWarningMsg:  
  14.         txt = QString("Warning: %1").arg(msg);  
  15.     break;  
  16.     case QtCriticalMsg:  
  17.         txt = QString("Critical: %1").arg(msg);  
  18.     break;  
  19.     case QtFatalMsg:  
  20.         txt = QString("Fatal: %1").arg(msg);  
  21.         abort();  
  22.     }  
  23.    
  24.     QFile outFile("debug.log");  
  25.     outFile.open(QIODevice::WriteOnly | QIODevice::Append);  
  26.     QTextStream ts(&outFile);  
  27.     ts << txt << endl;  
  28. }  
  29.    
  30. int main( int argc, char * argv[] )  
  31. {  
  32.     QApplication app( argc, argv );  
  33.    
  34.     //这个方法注册回调函数         
  35.     qInstallMsgHandler(customMessageHandler);     
  36.     ...  
  37.     return app.exec();  
  38. }  

 转自:http://wan-2004.iteye.com/blog/888963

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值