1 背景
在自己项目中,之前写好了几个模块,用了很多的qDebug()打印信息,后面项目经理要求有日志输出,以便以后出现问题方便调试,百度查了下,很容易得到自己想要的。。
2 介绍
用qInstallMessageHandler()这个全局函数就可以把qDebug(), qWarning()输出重定向的日志文件中,这个函数需要传个参数,实际就是一个回调函数,格式如下`void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg),type:消息等级, context包括:文件,行号,函数名等, msg:qDebug()时传递的参数。
3 实现
在myMessageOutput()函数中的步骤如下
1. 在当前路径下创建日志目录
2. 根据日期创建日志文件
3. 保留七天的日志文件
4. 拼接消息内容:msg+函数名+文件路径+行号
5. 文本流输入到日志文件
#include <QApplication>
#include <stdio.h>
#include <stdlib.h>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#define LOG_FILE_KEEP_NUM 7
void myMessageOutput(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