QT输出调试日志

   程序调试中需要保存qDebug的打印信息,首先想到的是Linux重定向输出到一个文件中,但是qdebug不行。google发现Qt已经自带了保存log的方法。


   
   
  1. #include <QtGui/QApplication>
  2. #include <QTextCodec>

   
   
  1. #include <QDebug>
  2. void customMessageHandler(QtMsgType type, const char *msg)
  3. {
  4. QString txt;
  5. switch (type) {
  6. //调试信息提示
  7. case QtDebugMsg:
  8. txt = QString( "Debug: %1").arg(msg);
  9. break;
  10. //一般的warning提示
  11. case QtWarningMsg:
  12. txt = QString( "Warning: %1").arg(msg);
  13. break;
  14. //严重错误提示
  15. case QtCriticalMsg:
  16. txt = QString( "Critical: %1").arg(msg);
  17. break;
  18. //致命错误提示
  19. case QtFatalMsg:
  20. txt = QString( "Fatal: %1").arg(msg);
  21. abort();
  22. }
  23. QFile outFile1("debuglog1.txt");
  24. QFile outFile2("debuglog2.txt");
  25. outFile1.open(QIODevice::WriteOnly | QIODevice::Append);
  26. if(outFile1.size() >= 1024* 10 )
  27. {
  28. outFile1.close();
  29. outFile2.remove();
  30. QFile::copy( "debuglog1.txt", "debuglog2.txt");
  31. outFile1.remove();
  32. QFile outFile3("debuglog1.txt");
  33. outFile3.open(QIODevice::WriteOnly | QIODevice::Append);
  34. QTextStream ts(&outFile3);
  35. ts << txt << endl;
  36. }
  37. else
  38. {
  39. QTextStream ts(&outFile1);
  40. ts << txt << endl;
  41. }
  42. }
  43. int main(int argc, char *argv[])
  44. {
  45. QApplication a(argc, argv);
  46. qInstallMsgHandler(customMessageHandler);
  47. MainServer mainWin;
  48. mainWin.show();
  49. return a.exec();
  50. }

debuglog1.txt 如果大于10k了,就复制到debuglog2.txt,同时删除debuglog1.txt,重新开始写

PS:bool QFile::copy ( const QString & fileName, const QString & newName ) [static]
This is an overloaded function.


Copies the file fileName to newName. Returns true if successful; otherwise returns false.


If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值