Qt 之 自定义日志文件,QtMessageHandler应用

目录

一、前言

二、头文件代码

三、源文件代码

四、使用示例

五、使用效果


一、前言

在qt程序发布后,还需要查看一些调试输出信息,一般将输出信息写入日志文件,本文通过自定义函数实现将Debug、Warning、Critical、Fatal及Info信息自动输出到日志文件内,只需在main函数加两行代码即可。

另外为了防止日志文件输出太多,防止文件过大,加入了文件超过最大限度自动覆盖重写功能,例如设置的日志文件大小不超过1M,那么超过1M后可以将之前的内容清除掉,只保留最新的1M。

二、头文件代码

loger.h

cpp 复制代码
#pragma once

#include <QMutex>
#include <QString>

#define LOG_FILE_NAME QString("/Log/") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + QString(".log")
#define MAX_SIZE 1024 * 1024 //文件最大1M

static int s_logLevel = QtDebugMsg;
static QMutex s_logMutex;
static QString s_logPath;

void setLogPath(const QString& path);
void setLogLevel(int level);
void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg);

三、源文件代码

loger.cpp

cpp 复制代码
#include "loger.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextStream>
#include <QDateTime>


void setLogPath(const QString& path)
{
	s_logPath = path;
}

void setLogLevel(int level)
{
	s_logLevel = level;
}

bool static ensureDirExist(const QString& dirPath)
{
	QDir dir(dirPath);
	if (dir.exists())
	{
		return true;
	}

	return dir.mkpath(dirPath);
}

void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
	if (type < s_logLevel)
	{
		return;
	}

	QString logInfo;
	QString logTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss.zzz");
	switch (type)
	{
	case QtDebugMsg:
		logInfo = QString("%1 [Debug] %2").arg(logTime, msg);
		break;

	case QtWarningMsg:
		logInfo = QString("%1 [Warning] %2").arg(logTime, msg);
		break;

	case QtCriticalMsg:
		logInfo = QString("%1 [Critical] %2").arg(logTime, msg);
		break;

	case QtFatalMsg:
		logInfo = QString("%1 [Fatal] %2").arg(logTime, msg);
		abort();
	case QtInfoMsg:
		logInfo = QString("%1 [Info] %2").arg(logTime, msg);
		break;
	}

	s_logMutex.lock();
	QFile outFile(s_logPath);
	QFileInfo fileInfo(outFile);
	if (!ensureDirExist(fileInfo.absoluteDir().absolutePath()))
		return;

	if (outFile.size() > MAX_SIZE)
	{
		if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text))
			return;
	}
	else
	{
		if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
			return;
	}

	QTextStream ts(&outFile);
	ts << logInfo.toUtf8() << endl;
	outFile.close();
	s_logMutex.unlock();
}

四、使用示例

cpp 复制代码
#include "loger.h"

int main(int argc, char *argv[])
{
    setLogPath("./" + LOG_FILE_NAME);
    qInstallMessageHandler(customLogMessageHandler);

    //...其他代码.....

}

在main函数加上上述代码即可,后面运行代码,使用qDebug、qInfo...等输出的内容将不会在控制台再输出,全部在日志文件内。

五、使用效果

相关推荐
憧憬成为原神糕手24 分钟前
c++_list
开发语言·c++
zyh2005043025 分钟前
c++的decltype关键字
c++·decltype
idealzouhu26 分钟前
Java 并发编程 —— AQS 抽象队列同步器
java·开发语言
爱吃油淋鸡的莫何26 分钟前
Conda新建python虚拟环境问题
开发语言·python·conda
闲人编程34 分钟前
Python实现日志采集功能
开发语言·python·fluentd·filebeat·日志采集
Sol-itude40 分钟前
关于MATLAB计算3维图的向量夹角总是不正确的问题记录
开发语言·matlab·问题解决·向量
2401_8628867843 分钟前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
奔驰的小野码1 小时前
java通过org.eclipse.milo实现OPCUA客户端进行连接和订阅
java·开发语言
小川_wenxun1 小时前
优先级队列(堆)
java·开发语言·算法
惜缘若水1 小时前
【SpinalHDL】Scala编程之伴生对象
开发语言·scala·spinalhdl