生活随笔
收集整理的這篇文章主要介紹了
qt日志
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在程序的運(yùn)行過程中,debug版的可以調(diào)試,查看輸出信息,release版的程序在運(yùn)行過程中一旦出現(xiàn)崩潰等問題,使得無法查看問題發(fā)生的點(diǎn),于是在項(xiàng)目中添加日志,變得極為重要。
此日志可以在程序debug版的時(shí)候,不生成日志,直接通過控制臺(tái)查看輸出信息,在release版的情況下可以生成日志,供查閱。
具體代碼如下:
log.hpp
#ifndef LOG_H
#define LOG_H#include <QCoreApplication>
#include <QDebug>#ifdef OUTPUT_LOG
#define outPut qOut
#else
#define outPut qDebug()
#endif
#define LOG_FILE QCoreApplication::applicationDirPath() + "/logger.txt"
#define qOut qDebug()<<__FUNCTION__<<"["<<__LINE__<<"]"
#define xErrPrint qCritical()<<__FUNCTION__<<"["<<__LINE__<<"]"#endif
在release版的時(shí)候打開#define OUTPUT_LOG宏定義的注釋,這樣在release版程序的運(yùn)行目錄下會(huì)生成日志文件,debug版程序可以不用打開#define OUTPUT_LOG的注釋。
main.cpp
#include "maindialog.h"#include <QApplication>
#include <QFile>
#include "log.hpp"
#include <QMutex>
#include <QDateTime>
#include <QScreen>void MessageTypePut(QtMsgType type
, const QMessageLogContext
&context
, const QString
&msg
);int main(int argc
, char *argv
[])
{
#ifdef OUTPUT_LOGqInstallMessageHandler(MessageTypePut
);
#endifQApplication
a(argc
, argv
);QString qss
;QString strNameqss
;QScreen
*screenPrimary
=QGuiApplication
::primaryScreen();QRect screen
=screenPrimary
->availableGeometry();if(screen
.width() > BASE_W
&& screen
.height() > BASE_H
){strNameqss
= ":/guangdianadjust.qss";outPut
<<"讀取QSS文件guangdianadjust.qss";}else{strNameqss
= ":/guangdian.qss";}QFile
qssFile(strNameqss
);qssFile
.open(QFile
::ReadOnly
);if(qssFile
.isOpen()){qss
= QString(qssFile
.readAll());a
.setStyleSheet(qss
);qssFile
.close();}MainDialog w
;w
.show();return a
.exec();
}void MessageTypePut(QtMsgType type
, const QMessageLogContext
&context
, const QString
&msg
)
{
static QMutex mutex
;mutex
.lock();QString text
;switch(type
){case QtDebugMsg
:text
= QString("Debug:");break;case QtWarningMsg
:text
= QString("Warning:");break;case QtCriticalMsg
:text
= QString("Critical:");break;case QtFatalMsg
:text
= QString("Fatal:");break;default:break;}QString current_date_time
= QDateTime
::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");QString message
= QString("%1 %2%3").arg(current_date_time
).arg(text
).arg(msg
);QFile
file(LOG_FILE
);file
.open(QIODevice
::WriteOnly
| QIODevice
::Append
);QTextStream
text_stream(&file
);text_stream
<< message
<< "\r\n";file
.flush();file
.close();mutex
.unlock();
}
在需要日志輸出的地方調(diào)用output輸出,使用方法和qDebug()相似,需要包含頭文件#include “l(fā)og.hpp”。
使用案例:
#include "log.hpp"str
= QCoreApplication
::applicationDirPath();str
+= "\\11.png";outPut
<<"路徑名:"<<str
;
在主函數(shù)中安裝消息句柄,首先聲明這個(gè)函數(shù)MessageTypePut,按照這樣就可以實(shí)現(xiàn)一個(gè)簡單的日志輸出。并在release版的程序生成日志,在debug版直接在輸出臺(tái)輸出信息。
總結(jié)
以上是生活随笔為你收集整理的qt日志的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。