实现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.         //以后就可以像下面这样直接打日志到文件中,而且日志也会包含时间信息
  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

你可能感兴趣的:(qt,include)