實現Qt日誌輸出到檔案
阿新 • • 發佈:2019-02-17
- #include <QtDebug>
- #include <QFile>
- #include <QTextStream >
- void customMessageHandler(QtMsgType type, const char *msg)
- {
- QString txt;
- switch (type)
- {
- case QtDebugMsg: //除錯資訊提示
- txt = QString("Debug: %1").arg(msg);
- break;
- case QtWarningMsg: //一般的warning提示
- txt = QString("Warning: %1").arg(msg);
- break;
- case QtCriticalMsg: //嚴重錯誤提示
- txt = QString("Critical: %1").arg(msg);
- break;
- case QtFatalMsg: //致命錯誤提示
- txt = QString("Fatal: %1").arg(msg);
- abort();
- default:
- break;
- }
- QFile outFile("Log.txt");
- outFile.open(QIODevice::WriteOnly | QIODevice::Append);
- QTextStream ts(&outFile);
- ts << txt << endl;
- }
- int main( int argc, char * argv[] )
- {
- QApplication app( argc, argv );
- //先註冊自己的MsgHandler
- qInstallMsgHandler(customMessageHandler);
- //以後就可以像下面這樣直接打日誌到檔案中,而且日誌也會包含時間資訊
- qDebug("This is a debug message at thisisqt.com");
- qWarning("This is a warning message at thisisqt.com");
- qCritical("This is a critical message at thisisqt.com");
- qFatal("This is a fatal message at thisisqt.com");
- return app.exec();
- }