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

五、使用效果

相关推荐
方传旺6 分钟前
C++17 std::optional 深拷贝 vs 引用:unordered_map 查询大对象性能对比
c++
Dontla22 分钟前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
后台开发者Ethan22 分钟前
Python需要了解的一些知识
开发语言·人工智能·python
何妨重温wdys1 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
重启的码农1 小时前
ggml 介绍 (6) 后端 (ggml_backend)
c++·人工智能·神经网络
重启的码农1 小时前
ggml介绍 (7)后端缓冲区 (ggml_backend_buffer)
c++·人工智能·神经网络
常利兵1 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
雨落倾城夏未凉1 小时前
5.通过拷贝构造函数复制一个对象,假如对象的成员中有个指针类型的变量,如何避免拷贝出来的副本中的该成员之下行同一块内存(等价于默认拷贝构造函数有没有缺点)
c++·后端
幼稚园的山代王1 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin
雨落倾城夏未凉1 小时前
4.深拷贝VS浅拷贝
c++·后端