Qt4 Qt5 qDebug輸出到檔案

2021-07-22 08:26:35 字數 2738 閱讀 2582

在qt中qdebug()可以可以列印出十分細緻的log,用過你就會喜歡。現在要將qdebug() 等重定向到檔案中。

但是qt4.***版本(qt5以下)和qt5以上版本中qdebug()重定向是有區別的。

一、在qt4.***版本(qt5以下)

使用使用qt的messagehandler可以將訊息重定向。在qt4.x時代,安裝乙個訊息處理器是用qinstallmsghandler() 

函式來安裝這個函式接受的乙個函式指標作為引數,函式的定義是

void functionname(qtmsgtype

,const

char

*);

如筆者自定義函式

void

messageoutput

(qtmsgtype

,const

char

*msg

)

txtmessage += qstring("\r\n");
qfile

file

(qobject

::tr

("c:\\qdebug.txt"

));

if(file.

open

(qiodevice

::writeonly

|qiodevice

::))

file.flush();

file.close();

mutex.unlock();

}

int

main(

intargc,

char

*argv)

qdebug.txt 輸出資訊如下

[10:30:58.792][debug] this is a debug message.

[10:30:59.754][warning] this is a warning message.

[10:31:00.056][critical] this is a critical message.

二、在qt5以上版本中

上述函式是編譯不通過,因為qinstallmsghandler()函式已經被廢棄掉。因為qt 5.x後,這個函式被qinstallmessagehandler()

所替代了。

這個函式同樣接受乙個函式指標作為引數,函式的定義是 void functionname(qtmsgtype,const qmessagelogcontext& cosnt qstring&),可見,該函式中多了乙個qmessagelogcontext引數。這個引數包含了debug的一些基本資訊(**所在檔案資訊、**所在行號、錯誤型別、版本號、當前函式名),例如該debug所在的函式,所在的檔案,所在的行數等。可以讓debug更加詳細。

如筆者下面例子

void

messageoutput(

qtmsgtype

type,

const

qmessagelogcontext

&context,

const

qstring

&msg)

txtmessage

+=qstring

(","

).arg(context.

line

);

txtmessage

+=qstring

("\r\n"

);

//輸出到檔案(寫,追加模式)

qfile

file(

"c:\\qdebug.txt"

);

if(file.

open

(qiodevice

::writeonly

|qiodevice

::))

file.flush();
file.

close

();

//解鎖

mutex.unlock();
}
int

main(

intargc,

char

*argv)

qdebug.txt輸出資訊如下:

[10:30:58.792][..\qdebug_5\main.cpp][int __cdecl main(int,char *)][debug] this is a debug message.,

[10:30:59.754][..\qdebug_5\main.cpp][int __cdecl main(int,char *)][warning] this is a warning message.,

[10:31:00.056][..\qdebug_5\main.cpp][int __cdecl main(int,char *)][critical] this is a critical message.,

可見 qt5以上版本qdebug可以輸出更加詳細資訊來格式log。

Qt自定義qDebug輸出

qdebug預設輸出字串 換行 想要輸出檔名,函式名,行號需要自定義,如下是輸出到檔案,並且列印到控制台 自定義訊息處理函式 void mymessageoutput qtmsgtype type,const qmessagelogcontext context,const qstring msg ...

Qt除錯資訊分類和qDebug 匯出到文

本文主要參考 一去 二三里 的博文 qt之日誌輸出檔案和 qt之日誌輸出視窗以及qt的幫助文件,index qinstallmessagehandler 並對他們進行了一些分析和優化。1,qinstallmessagehandler 的原理,應該是 publisher subscriber 發布 訂...

qt中qDebug 無法輸出解決辦法

在除錯qt程式,無論是debug版本還是release版本,都會遇到此類問題,先將其總結在此。無論是標頭檔案還是原始檔中都有 include 程式中qdebug 的使用方法都正確 卻在輸出視窗中無法看到輸出的資訊。1.在工程檔案.pro的最後新增 config console 2.如果你的工程檔案中...