Qt 日誌輸出

2021-09-11 02:07:09 字數 2224 閱讀 2974

為了方便進行現場除錯,我們需要使用日誌記錄我們關心的資料資訊,而qt提供了日誌系統非常方便,只需要我們提供乙個函式指標即可,定義如下

void mymessagehandler(qtmsgtype, const qmessagelogcontext &, const qstring &);

通常,實現如下

void outputmessage(qtmsgtype type, const qmessagelogcontext &context, const qstring &msg)

qstring contextinfo = qstring("file:(%1) line:(%2)").arg(qstring(context.file)).arg(context.line);

qstring currentdatetime = qdatetime::currentdatetime().tostring("yyyy-mm-dd hh:mm:ss ddd");

qstring currentdate = qstring("(%1)").arg(currentdatetime);

qstring message = qstring("%1 %2 %3 %4").arg(text).arg(contextinfo).arg(msg).arg(currentdate);

qfile file("log.txt");

qtextstream text_stream(&file);

text_stream << message << "\r\n";

file.flush();

file.close();

mutex.unlock();

}

使用
int main(int argc, char *ar**)

這樣既捕獲了我們**中qdebug()的輸出,重置時,qinstallmessagehandler(0)即可。但是,由於涉及檔案io,這樣的耗時操作往往需要執行緒配合,我們優化如下

日誌資訊

class loger : public qobject

;static loger* g_log = nullptr;

loger::loger(qobject *parent) : qobject(parent)

void loger::outputmessage(qtmsgtype type, const qmessagelogcontext &context, const qstring &msg)

qstring contextinfo = qstring("file:(%1) line:(%2)").arg(qstring(context.file)).arg(context.line);

qstring currentdatetime = qdatetime::currentdatetime().tostring("yyyy-mm-dd hh:mm:ss ddd");

qstring currentdate = qstring("(%1)").arg(currentdatetime);

qstring message = qstring("%1 %2 %3 %4").arg(text).arg(contextinfo).arg(msg).arg(currentdate);

emit g_log->sig_sendmessage(message);

}

日誌寫入

class logwrite : public qobject

;logwrite::logwrite(qobject *parent) : qobject(parent)

logwrite::~logwrite()

void logwrite::slot_writeinfo(qstring info)

使用

loger log;

logwrite logwrite;

qinstallmessagehandler(&loger::outputmessage);

qobject::connect(&log, &loger::sig_sendmessage, &logwrite, &logwrite::slot_writeinfo);

由於,寫入log位於執行緒中,即連線方式為佇列,因此相當安全。

本想著使用qt執行緒的高階模組,對此的問題仍然。

QT 輸出日誌

qtmessagehandler qinstallmessagehandler qtmessagehandler handler qinstallmessagehandler來實現輸出詳細日誌,輸出檔名,行號,所在函式及事件,並寫入檔案。最後呼叫系統原來的函式,使資訊像之前一樣輸出到除錯視窗,便於開...

qt日誌實現

qt的日誌有四個級別 qdebug 除錯資訊 qwarning 警告資訊 qcritical 嚴重錯誤 qfatal 致命錯誤 可以通過下的 void qcritical const char msg,void qdebug const char msg,void qfatal const char...

Qt 日誌檔案

qt 列印資訊等級 型別描述 qdebug 除錯資訊 qinfo 一般資訊 qwarning 警告資訊 qcritical 危險資訊 qfatal 致命資訊 注 使用qfatal列印資訊後,程式會終止 自定義日誌輸出資訊 qtmessagehandler qinstallmessagehandler...