当前位置: 首页 > news >正文

Qt将打印信息输出到文件

将打印信息(qDebug、qInfo、qWarning、qCritial等)输出到指定文件来以实现简单的日志功能。

#include "mainwindow.h"
#include <QApplication>
#include <QLoggingCategory>
#include <QMutex>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
QString logDirName = "log";
QMutex mutex;
void logInit();
void message(QtMsgType type, const QMessageLogContext &context, const QString &msg);
int main(int argc, char *argv[])
{logInit();QApplication a(argc, argv);qDebug()<<"aaaa";MainWindow w;w.show();return a.exec();
}void logInit()
{QDir dir(logDirName);// 不存在log目录就先创建if (!dir.exists()) QDir().mkdir(logDirName);// 遍历日志目录所有日志文件,然后删除十天前的日志文件QFileInfoList logList = dir.entryInfoList({"*.txt"}, QDir::Files, QDir::Time);foreach (const QFileInfo &info, logList) {if (info.created().daysTo(QDateTime::currentDateTime()) > 10) dir.remove(info.fileName());}QLoggingCategory::setFilterRules("*.info=true\n");qInstallMessageHandler(message);
}void message(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{mutex.lock();QString text = QString();switch (type) {case QtDebugMsg:text = "Debug";break;case QtWarningMsg:text = "Warning";break;case QtCriticalMsg:text = "Critical";break;case QtInfoMsg:text = "Info";break;case QtFatalMsg:text = "Fatal";break;default:break;}QString log= QString("[%1:%2:%3:%4]%5:%6").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(context.file).arg(context.function).arg(context.line).arg(text).arg(msg);static QString path = QDir::cleanPath(logDirName+QDir::separator()+QDateTime::currentDateTime().toString("yyyyMMdd-hhmmsszzz")+QString("LOG.txt"));QFile file(path);if (file.open(QIODevice::WriteOnly|QIODevice::Append)) {QTextStream stream(&file);stream<<log<<endl;file.flush();file.close();}mutex.unlock();
}

该项目内所有打印信息将会输出到指定文件,比如在主界面mainwindow中点击按钮印一句d

void MainWindow::on_pushButton_clicked()
{qDebug()<<"11111";
}

程序运行后,不停点击按钮,可以看到有生成对应文件

http://www.lryc.cn/news/252041.html

相关文章:

  • 【risc-v】易灵思efinix FPGA sapphire_soc IP配置参数分享
  • 直播的种类及类型
  • 时间序列数据压缩算法简述
  • 智能锁-SI522TORC522方案资料
  • redux(4) -RTK简单使用
  • 开源运维监控系统-Nightingale(夜莺)应用实践(未完)
  • 深入理解GMP模型
  • 数学建模-基于集成学习的共享单车异常检测的研究
  • C语言-内存分配
  • 算法工程师-机器学习面试题总结(1)
  • 【蓝桥杯选拔赛真题73】Scratch烟花特效 少儿编程scratch图形化编程 蓝桥杯创意编程选拔赛真题解析
  • Juniper EX系列交换机端口配置操作
  • 2.1 Linux C 编程
  • 服务器数据恢复—ocfs2文件系统被格式化为其他文件系统如何恢复数据?
  • 海云安参与制定《信息安全技术 移动互联网应用程序(App)软件开发工具包(SDK)安全要求》标准正式发布
  • 如何调用 API | 学习笔记
  • 关于云备份项目的HTTP协议字段理解
  • 掉落的俄罗斯方块
  • 医院不良事件报告系统源码带鱼骨图分析
  • 数据库相关算法题 V3
  • 第二证券:本周3只新股申购,大豆蛋白行业领军企业来了!
  • 【go语言开发】loglus日志框架的使用
  • 【Unity动画】Unity 动画播放的流程
  • 深度学习——第3章 Python程序设计语言(3.2 Python程序流程控制)
  • EasyExcel生成多sheet页的excel
  • 家用小型洗衣机哪款性价比高?内衣洗衣机品牌推荐
  • 为何Go爬虫依然远没有Python爬虫流行
  • 【华为OD题库-057】MELON的难题-java
  • OGG实现Oracle19C到postgreSQL14的实时同步
  • windows 你的电脑不能投影到其他屏幕,请尝试重新安装驱动程序