Qt应用程序开发三:写日志文件

开发过程中写日志文件是必不可少

Qt中自带qInstallMessageHandler来进行日志的收集

使用方法

第一步:设置qInstallMessageHandler的回调函数:

#include "CsdnDemo.h"
#include <QApplication>
#include<QTranslator>
#include<QDateTime>
#include<QMutex>
#include<QFile>
#include<QTextStream>

//日志文件名称
#define LOG_FILE     qApp->applicationDirPath()+"/logger.txt"

//日志收集回调函数
void MessageOutPut(QtMsgType type, const QMessageLogContext &context, const QString &msg);

int main(int argc, char *argv[])
{
    qInstallMessageHandler(MessageOutPut);
    QApplication a(argc, argv);
    CsdnDemo w;
    w.show();

    return a.exec();
}


void MessageOutPut(QtMsgType type, const QMessageLogContext &context, const QString &msg)

{
    static QMutex mutex;
    mutex.lock();
    QString text;
   switch(type)
   {
   case QtDebugMsg:
       text = QString("Debug:");
       break;

   case QtWarningMsg:
       text = QString("Warning:");
       break;

   case QtCriticalMsg:
       text = QString("Critical:");
       break;

   case QtFatalMsg:
       text = QString("Fatal:");
       break;
   default:
       break;
   }
   //日志写到文件
   QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
   QString message = QString("%1 %2%3").arg(current_date_time).arg(text).arg(msg);
   QFile file(LOG_FILE);
   file.open(QIODevice::WriteOnly | QIODevice::Append);
   QTextStream text_stream(&file);
   text_stream << message << "\r\n";
   file.flush();
   file.close();
   mutex.unlock();

}

第二步调用:

例如:

#ifndef CONFIG_H
#define CONFIG_H
#include<QDebug>
#define xPrint qDebug()<<__FUNCTION__<<"["<<__LINE__<<"]"
#define xErrPrint  qCritical()<<__FUNCTION__<<"["<<__LINE__<<"]"

#endif // CONFIG_H
#include "CsdnDemo.h"
#include "ui_CsdnDemo.h"
#include"config.h"
#include<QFile>


#pragma execution_character_set("utf-8")

CsdnDemo::CsdnDemo(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CsdnDemo)
{
    ui->setupUi(this);
    load("test.txt");
}
void  CsdnDemo::load(const QString fileName)
  {
      QFile file(fileName);
      xPrint<<fileName;
      if (!file.exists()){
            xErrPrint<<QString("File '%1' does not exist!").arg(fileName);
      }

  }

运行结果会在指定日志路径下生成looger.txt

内容为

 

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值