QT输出调试日志

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


   
   
     
     
     
     
  1. #include
  2. #include

   
   
     
     
     
     
  1. #include
  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).



你可能感兴趣的:(Qt,qt日志)