在Qt开发过程当中经常使用qDebug等一些输出来调试程序,但是到了正式发布的时候,都会被注释或者删除,采用日志输出来代替。
以下demo实现的功能:
- 将调试的log信息输出到文件
- log文件保存位置:当前程序运行的路径->debugs文件夹
- 实时log文件为debug.log文件,当该文件大小超过20M时,按照时间重命名该文件。
- debugs文件夹中的文件达到最大规定的数量时,删除多余的log文件。
Demo
- logOutput.cpp
#include <QDebug>
#include <QMutex>
class LogOutput:public QThread /*继承QThread类,使log输出另起线程,不干扰主线程*/
{
protected:
void run();/*复写QThread的run函数*/
};/*定义导出log的类*/
void LogOutput::run(){/*定义成员函数*/
qInstallMessageHandler(customMessageHandler);/*使用Qt自带的qInstallMessageHandler函数,导出log*/
}
void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;/*线程锁,防止多个文件同时打log时,log部分缺失*/
mutex.lock();
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();
}
txt = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") + " " + txt;
QString path=QCoreApplication::applicationDirPath()+"/debugs";/*保存log文件的路径*/
QDir dir(path);
if(!dir.exists()){
dir.mkdir(path);
}
QFile outFile(path+"/debug.log");
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
if(outFile.exists() && (outFile.size() >= 20*1024*1024)){
QDateTime time = QDateTime::currentDateTime(); //获取系统当前时间
QString str = time.toString("yyyy-MM-dd hh-mm-ss");
outFile.close();
QFile::rename(path+"/debug.log",path+"/log" + str + ".log");/*当前log输出文件debug.log重命名*/
QFileInfoList fileList;
fileList = dir.entryInfoList(QDir::Dirs|QDir::Files
|QDir::Readable|QDir::Writable
|QDir::Hidden|QDir::NoDotAndDotDot
,QDir::Name);
int infoNum = fileList.size();/*当前文件夹的log数量*/
if(infoNum > 512){
QFile fileTemp(fileList.at(0).filePath());
fileTemp.remove();
fileList.removeAt(0);
}//若数量达到一定值,则删除多余的log文件
}else{
QTextStream ts(&outFile); /*输出log到文件*/
ts << txt << endl;
}
mutex.unlock();
}
- main.cpp中的相关使用
LogOutput logOutput;
logOutput.start();/*开启log输出的线程,线程开启后,默认调用run函数*/