3.QT中的debug相關的函式,以及檔案鎖的使用
1新建專案T33Debug
main.cpp
#include<QDebug>
#include<QFile>
#include<QMutex>//檔案鎖
voidMyMessageHandler(QtMsgTypetype,constQMessageLogContext&context,constQString&msg)
{
//使用一個檔案鎖,當在寫檔案的時候,要等寫完之後才能繼續執行
staticQMutexmutex;
mutex.lock();
QStringstrContext;
//在QMessageLogContext
strContext.sprintf("%s%d%s:\r\n\t",context.file,context.line,context.function);
QStringoutput=strContext+msg+"\r\n";
if(type==QtDebugMsg)
{
QFilefile("debug.log");
file.open(QFile::WriteOnly|QFile::Append);
file.write(output.toUtf8());
file.close();
}
if(type==QtWarningMsg
{
QFilefile("warning.log");
file.open(QFile::WriteOnly|QFile::Append);
file.write(output.toUtf8());
file.close();
}
if(type==QtCriticalMsg)
{
QFilefile("critical.log");
file.open(QFile::WriteOnly|QFile::Append);
file.write(output.toUtf8());
file.close();
}
if(type==QtFatalMsg)
{
QFile
file.open(QFile::WriteOnly|QFile::Append);
file.write(output.toUtf8());
file.close();
}
printf("%s",output.toUtf8().data());
mutex.unlock();
}
intmain()
{
//Tosuppresstheoutputatruntime,installyourownmessage
//handlerwithqInstallMessageHandler().
qInstallMessageHandler(MyMessageHandler);
qDebug()<<"outputdebug";
qDebug("%s,%d","outputdebug",1);
qWarning()<<"warning";
qCritical()<<"cridical";
//可以放開下面的一句,然後發現目錄也有相應的fatal.log檔案
//qFatal("fatalinfo");
}
執行結果:
輸入目錄(E:\QT\build-T33Debug-Desktop_Qt_5_3_MinGW_32bit-Debug)的檔案如下: