實現Qt日誌輸出到檔案

來源:互聯網
上載者:User
  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.         //以後就可以像下面這樣直接打日誌到檔案中,而且日誌也會包含時間資訊
  36.         qDebug("This is a debug message at thisisqt.com");
  37.         qWarning("This is a warning message  at thisisqt.com");
  38.         qCritical("This is a critical message  at thisisqt.com");
  39.         qFatal("This is a fatal message at thisisqt.com");
  40.         return app.exec();
  41. }

以上引自http://www.thisisqt.com/forum/viewthread.php?tid=90

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.