QT:Log日誌功能實現
阿新 • • 發佈:2018-12-10
1.簡介
在利用QT進行開發的過程中經常會用到qDebug()來輸出除錯資訊,但當程式正式釋出時,這些都會被註釋或者刪除,這時我們就需要通過Log日誌輸出來代替。
Log日誌是專案當中比用的功能,以便系統有錯誤是能夠快速跟蹤、定位,QT中提供類似的機制。在QT4中是通過Qt::qInstallMsgHandler()實現,但在QT5中使用了新的Qt::qInstallMessageHandler()來代替,詳情請檢視QT助手。
2.QT除錯級別
- qDebug() 除錯訊息
- qInfo() 資訊訊息
- qWarning() 警告訊息和可恢復的錯誤
- qCritical() 關鍵錯誤和系統錯誤
- qFatal() 致命錯誤
3.程式碼
#include <QCoreApplication> #include <QFile> #include <QMutex> // 互鎖標頭檔案 #include <QTextStream> #include <QDateTime> void MessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { static QMutex mutex; mutex.lock(); QString text; switch (type) { case QtDebugMsg: text = QString("Debug:"); break; case QtInfoMsg: text = QString("Info:"); break; case QtWarningMsg: text = QString("Warning:"); break; case QtCriticalMsg: text = QString("Critical:"); break; case QtFatalMsg: text = QString("Fatal:"); default: break; } QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line); QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd"); QString currentDate = QString("(%1)").arg(currentTime); QString message = QString::fromLocal8Bit("【%1】%2 %3 %4").arg(currentTime).arg(text).arg(msg).arg(context_info); QString path = QCoreApplication::applicationDirPath(); QFile file(path + "/log.txt"); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream textStream(&file); textStream << message << "\r\n"; file.flush(); file.close(); mutex.unlock(); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qInstallMessageHandler(MessageHandler); //列印日誌到檔案中 qDebug("This is a debug message"); // qDebug:除錯資訊 qInfo("This is a information message"); // Info: 資訊訊息 qWarning("This is a warning message"); // qWarning:警告資訊 qCritical("This is a critical message"); // qCritical:嚴重錯誤 qFatal("This is a fatal message"); // qFatal:致命錯誤(會報錯,然後準備退出) return a.exec(); }
在這使用QMutex進行加鎖、解鎖操作,便於我們可以安全的在多執行緒操作中使用。QFile開啟模式為QIODevice::ReadWrite | QIODevice::Append
(讀寫、追加模式),保證了輸出資訊可以以追加的形式寫入檔案。
4.結果:
5.注意
以上除錯結果資訊在Debug模式下輸出是沒問題的,但是在Release模式下是預設不輸出檔名、行號等資訊,
這時只需要在.pro檔案中加入以下巨集定義:
DEFINES += QT_MESSAGELOGCONTEXT
之後,重新qmake編譯既可以。