1. 背景
将项目里面的打印信息,通过日志记录,后续出现问题,方便记录。
2.介绍
用qInstallMessageHandler()这个全局函数就可以把qDebug(), qWarning()输出重定向的日志文件中,这个函数需要传个参数,实际就是一个回调函数,格式如下
`void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
参数详解:
type:消息等级
context包括:文件,行号,函数名等
msg:qDebug()时传递的参数。
3 实现
在customMessageHandle()函数中的步骤如下
1. 在当前路径下创建日志目录
2. 根据日期创建日志文件
3. 拼接消息内容:msg+函数名+文件路径+行号
4. 文本流输入到日志文件
#include <QApplication>
#include <QDebug>
void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
//#1 create directory that name is log
QDir dir("log");
if (!dir.exists())
{
QDir dir;
dir.mkdir("log");
}
//#2 create log file by current date ==> eg:log20170418.txt
QString currentDate = QDateTime::currentDateTime().toString("yyyyMMdd");
QString logName = "log" + currentDate + ".txt";
QString logFileName = "log/" + logName;
// 加锁
static QMutex mutex;
mutex.lock();
QFile file(logFileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Append))
{
file.close();
return ;
}
//#3 joint string
QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString logMsg;
switch (type)
{
case QtDebugMsg:
logMsg = QString("%1: [Debug]: %2 Function: %3 File: %4 Line: %5\n").arg(currentDateTime).arg(msg).arg(context.function).arg(context.file).arg(context.line);
break;
case QtInfoMsg:
logMsg = QString("%1: [Info]: %2 Function: %3 File: %4 Line: %5\n").arg(currentDateTime).arg(msg).arg(context.function).arg(context.file).arg(context.line);
break;
case QtWarningMsg:
logMsg = QString("%1: [Warning]: %2 Function: %3 Line: %4 File: %5\n").arg(currentDateTime).arg(msg).arg(context.function).arg(context.file).arg(context.line);
break;
case QtCriticalMsg:
logMsg = QString("%1: [Critical]: %2 Function: %3 Line: %4 File: %5\n").arg(currentDateTime).arg(msg).arg(context.function).arg(context.file).arg(context.line);
break;
case QtFatalMsg:
logMsg = QString("%1: [Fatal]: %2 Function: %3 Line: %4 File: %5\n").arg(currentDateTime).arg(msg).arg(context.function).arg(context.file).arg(context.line);
abort();
break;
default:
break;
}
//#4 log message out to file
QTextStream stream(&file);
stream << logMsg << "\r\n";;
file.flush();
file.close();
// 解锁
mutex.unlock();
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(customMessageHandler);
QApplication a(argc, argv);
qDebug() << "this is Debug";
qInfo() << "this is info";
qWarning() << "this is warning";
qCritical()<< "this is critical";
qFatal("this is fatal");
return a.exec();
}
这里,使用QMutex进行加锁、解锁操作,便于我们可以安全的在多线程操作中使用。QFile打开模式为QIODevice::ReadWrite | QIODevice::Append
(读写、追加模式),保证了输出信息可以以追加的形式写入文件。