程序调试中需要保存qDebug的打印信息,首先想到的是Linux重定向输出到一个文件中,但是qdebug不行。google发现Qt已经自带了保存log的方法。
-
#include
-
#include
-
#include
-
void customMessageHandler(QtMsgType type, const char *msg)
-
{
-
QString txt;
-
switch (type) {
-
//调试信息提示
-
case QtDebugMsg:
-
txt = QString(
"Debug: %1").arg(msg);
-
break;
-
//一般的warning提示
-
case QtWarningMsg:
-
txt = QString(
"Warning: %1").arg(msg);
-
break;
-
//严重错误提示
-
case QtCriticalMsg:
-
txt = QString(
"Critical: %1").arg(msg);
-
break;
-
//致命错误提示
-
case QtFatalMsg:
-
txt = QString(
"Fatal: %1").arg(msg);
-
abort();
-
}
-
-
QFile outFile1("debuglog1.txt");
-
QFile outFile2("debuglog2.txt");
-
outFile1.open(QIODevice::WriteOnly | QIODevice::Append);
-
if(outFile1.size() >=
1024*
10 )
-
{
-
outFile1.close();
-
outFile2.remove();
-
QFile::copy(
"debuglog1.txt",
"debuglog2.txt");
-
outFile1.remove();
-
-
QFile outFile3("debuglog1.txt");
-
outFile3.open(QIODevice::WriteOnly | QIODevice::Append);
-
QTextStream ts(&outFile3);
-
ts << txt <<
endl;
-
}
-
else
-
{
-
QTextStream ts(&outFile1);
-
ts << txt <<
endl;
-
}
-
}
-
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
qInstallMsgHandler(customMessageHandler);
-
-
MainServer mainWin;
-
-
mainWin.show();
-
-
return a.exec();
-
}
debuglog1.txt 如果大于10k了,就复制到debuglog2.txt,同时删除debuglog1.txt,重新开始写
PS:bool QFile::copy ( const QString & fileName, const QString & newName ) [static]
This is an overloaded function.
Copies the file fileName to newName. Returns true if successful; otherwise returns false.
If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).