前言
很多情况下,需要对Qt的程序进行日志打印,使用现有的QDebug等函数的重定向,写入到文件中。
代码
#include<QtDebug>
#include<QMutex>
#include<QFile>
#include<QDate>
#include<QDir>
#include <iostream>
using namespace std;
//#include "common/plotsetting.h"
//日志生成
void LogMsgOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
// 加锁
static QMutex mutex;
mutex.lock();
QByteArray localMsg = msg.toLocal8Bit();
QString strMsg("");
switch(type)
{
case QtDebugMsg:
strMsg = QString("Debug:");
break;
case QtWarningMsg:
strMsg = QString("Warning:");
break;
case QtCriticalMsg:
strMsg = QString("Critical:");
break;
case QtFatalMsg:
strMsg = QString("Fatal:");
break;
}
// 设置输出信息格式
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
QString strMessage = QString("%1 File:%2 Line:%3 Function:%4 DateTime:%5 Message:%6")
.arg(strMsg).arg(context.file).arg(context.line).arg(context.function).arg(strDateTime).arg(localMsg.constData());
// 输出信息至文件中(读写、追加形式)
QFile file("log.txt");
file.open(QIODevice::ReadWrite | QIODevice::Append);
QTextStream stream(&file);
stream << strMessage << "\r\n";
cout<<QString(localMsg.constData()).toStdString()<<endl;
file.flush();
file.close();
// 解锁
mutex.unlock();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qInstallMessageHandler(LogMsgOutput);
MainWindow w;
w.show();
return a.exec();
}
实现的效果是,即写入到日志文件中,又不影响控制台输出。