【Qt专栏】将调试信息输出到日志文件中


一、调试信息类型

前面两种输出调试信息,后面三个输出错误信息,严重级别依次增加:

  • qDebug():QtDebugMsg(调试信息)
    如果项目中定义了QT_NO_WARNING_OUTPUT,则不会执行此函数。
  • qInfo():QtInfoMsg(一般信息)
  • qWarning():QtWarningMsg(警告信息)
    如果项目中定义了QT_NO_WARNING_OUTPUT,则不会执行此函数。
  • qCritical():QtCriticalMsg(严重信息)
  • qFatal():QtFatalMsg(致命信息)
    默认实现将使程序中断。

二、日志消息处理API

  • qInstallMessageHandler(“回调函数”)
    安装消息处理函数,传入回调函数,输出调试信息的时候就调用此回调函数。
  • IsDebuggerPresent()
    判断当前是否处于调试环境,如果有调试器附加(如Dbgview工具),就不会将日志信息输出到日志文件中。
  • OutputDebugStringA(“日志信息”)
    调试信息的Windows API(ANSI版本),用来输出日志信息到日志文件或调试器。

三、日志信息输出接口

1.loginfo.h文件

#ifndef LOGINFO_H
#define LOGINFO_H

#include <QtGlobal>
#include <QFile>
#include <QDir>
#include <QDate>
#include <QTime>
#include <qt_windows.h>

class LogInfo
{
public:
    static void RecordLog();
private:
    static void outputLog(QtMsgType type,const QMessageLogContext &context,const QString &msg);
};

#endif // LOGINFO_H

2.loginfo.cpp文件

#include "loginfo.h"

void LogInfo::RecordLog()
{
    if(IsDebuggerPresent()){
        return;
    }
    qInstallMessageHandler(outputLog);  //安装消息处理函数
}

void LogInfo::outputLog(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QDir projectDir(QDir::currentPath());   //当前工程目录下
    const QString logDir = "log";
    if(!projectDir.exists(logDir)){
        projectDir.mkdir(logDir);
    }
    projectDir.cd(logDir);      //切换到日志目录下
    QString logPath = projectDir.filePath(QDate::currentDate().toString("yyyy-MM-dd")+".txt");

    QFile logFile(logPath);     //创建日志文件
    if(!logFile.open(QFile::Append | QFile::WriteOnly)){
        qInstallMessageHandler(0);  //恢复消息处理程序
        qDebug("ERROR OPEN LOG FILE");
        return;
    }

    QString tp = nullptr;
    switch (type){
    case QtDebugMsg:
        tp = "Debug";
        break;
    case QtInfoMsg:
        tp = "Info";
        break;
    case QtWarningMsg:
        tp = "Warning";
        break;
    case QtCriticalMsg:
        tp = "Critical";
        break;
    case QtFatalMsg:
        tp = "Fatal";
        break;
    default:
        break;
    }

    QString logLine = QString("%1%2    %3:%4:%5:%6    %7%8\r").arg("Time::").arg(QTime::currentTime().toString("hh:mm:ss"))
            .arg(tp).arg(context.file).arg(context.line).arg(context.function).arg("Log::").arg(msg);
    logFile.write(logLine.toUtf8());
    OutputDebugStringA(msg.toLocal8Bit());
}

3.调用方式

提示:在调用该接口之后,工程的调试信息才会输出到日志文件中
在mian函数里直接调用LogInfo::RecordLog()即可,记得加入头文件#include “loginfo.h”。


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拉伊卜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值