1. 程式人生 > >實現Qt日誌輸出到檔案

實現Qt日誌輸出到檔案

  1. #include <QtDebug>
  2. #include <QFile>
  3. #include <QTextStream >
  4. void customMessageHandler(QtMsgType type, const char *msg)
  5. {
  6.         QString txt;
  7.         switch (type)
  8.        {
  9.         case QtDebugMsg:     //除錯資訊提示
  10.                 txt = QString("Debug: %1").arg(msg);
  11.                 break;
  12.         case QtWarningMsg:  //一般的warning提示
  13.                 txt = QString("Warning: %1").arg(msg);
  14.                 break;
  15.         case QtCriticalMsg:    //嚴重錯誤提示
  16.                 txt = QString("Critical: %1").arg(msg);
  17.                 break;
  18.         case QtFatalMsg:      //致命錯誤提示
  19.                 txt = QString("Fatal: %1").arg(msg);
  20.                 abort();
  21.        default:
  22.                break;
  23.         }
  24.         QFile outFile("Log.txt");
  25.         outFile.open(QIODevice::WriteOnly | QIODevice::Append);
  26.         QTextStream ts(&outFile);
  27.         ts << txt << endl;
  28. }
  29. int main( int argc, char * argv[] )
  30. {
  31.         QApplication app( argc, argv );
  32.         //先註冊自己的MsgHandler
  33.         qInstallMsgHandler(customMessageHandler);       
  34.         //以後就可以像下面這樣直接打日誌到檔案中,而且日誌也會包含時間資訊
  35.         qDebug("This is a debug message at thisisqt.com");
  36.         qWarning("This is a warning message  at thisisqt.com");
  37.         qCritical("This is a critical message  at thisisqt.com");
  38.         qFatal("This is a fatal message at thisisqt.com");
  39.         return app.exec();
  40. }
以上引自http://www.thisisqt.com/forum/viewthread.php?tid=90