1.重写方法
using namespace std;
//日志代码互斥锁
QMutex logMutex;
QString timePoint;
void LogMsgOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
logMutex.lock();
QByteArray localMsg = msg.toLocal8Bit();
QString log;
//日志时间戳
log.append(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss "));
switch (type)
{
case QtDebugMsg:
{
log.append(QString("Debug: %1(FILE: %2:%3, FUNCTION: %4)
").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
break;
}
case QtInfoMsg:
{
log.append(QString("Info: %1(FILE: %2:%3, FUNCTION: %4)
").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
break;
}
case QtWarningMsg:
{
log.append(QString("Warning: %1(FILE: %2:%3, FUNCTION: %4)
").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
break;
}
case QtCriticalMsg:
{
log.append(QString("Critical: %1(FILE: %2:%3, FUNCTION: %4)
").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
break;
}
case QtFatalMsg:
{
log.append(QString("Fatal: %1(FILE: %2:%3, FUNCTION: %4)
").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
break;
}
}
QDir tempDir;
if (!tempDir.exists("./log"))
{
qDebug() << "log dir not exist" << endl;
tempDir.mkpath("./log");
}
QFile file;
QString path = QString("./log/%1.log").arg(timePoint);
file.setFileName(path);
if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
{
QString erinfo = file.errorString();
cout << erinfo.toStdString() << endl;
return;
}
QTextStream out(&file);
out << log << "\n\r";
file.flush();
file.close();
logMutex.unlock();
}
2.在main函数中安装自定义的方法
timePoint = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH_mm_ss");
qInstallMessageHandler(LogMsgOutput);
注意:
1)在编译release版本的时候日志文件中部分内容会为空,比如文件名、函数名和文件行数,因为Qt默认会去掉相关信息,解决方法是在pro文件中添加宏定义 DEFINES += QT_MESSAGELOGCONTEXT,如果是VS开发环境在配置项的C++预编译器中添加此宏,release版本的日志中就会有相关信息
2)在自定义日志handler中的qDebug不会有日志写入文件,因为一旦允许这样操作就会陷入无穷递归,所以上面代码中判断日志文件夹是否存在时的 qDebug() << "log dir not exist" << endl;不会在日志文件中出现,可参考Qt源文件qlogging.cpp的实现和说明