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...等输出的内容将不会在控制台再输出,全部在日志文件内。

五、使用效果

相关推荐
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧1 小时前
C语言_数据结构总结8:链式队列
c语言·开发语言·数据结构·链表·visualstudio·visual studio
千里码aicood1 小时前
[含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
开发语言·前端·python
讨厌下雨的天空1 小时前
C++之list
开发语言·c++·list
大麦大麦1 小时前
深入剖析 Sass:从基础到进阶的 CSS 预处理器应用指南
开发语言·前端·css·面试·rust·uni-app·sass
hhw1991122 小时前
c#面试题整理6
java·开发语言·c#
Icomi_2 小时前
【神经网络】0.深度学习基础:解锁深度学习,重塑未来的智能新引擎
c语言·c++·人工智能·python·深度学习·神经网络
蠟筆小新工程師2 小时前
Deepseek可以通过多种方式帮助CAD加速工作
开发语言·python·seepdeek
不知道取啥耶3 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
天道有情战天下3 小时前
python flask
开发语言·python·flask
zephyr_zeng4 小时前
VsCode + EIDE + OpenOCD + STM32(野火DAP) 开发环境配置
c语言·c++·vscode·stm32·单片机·嵌入式硬件·编辑器