QT应用编程: QDebug输出重定向到日志文件

一、环境介绍

操作系统介绍:win10 64位

QT版本: 5.12.6

二、功能介绍

初始化QDebug输出重定向到日志文件,重定向之后,程序里通过qDebug()<<"xxx"输出的数据都会保存到在日志文件中;程序发布之后方便查看日志文件.了解程序执行情况。

三、示例代码

#include "widget.h"

#include <QApplication>

void customMessageHandler(QtMsgType type, const QMessageLogContext &, const QString & str)
{
    QString txt=str;
    QString app_run_addr;
    //获取程序当前运行目录
    QString current_PathName = QCoreApplication::applicationDirPath();
    if(QFile::exists(current_PathName)==false)
    {
        app_run_addr="debug.log";
    }else
    {
        app_run_addr=current_PathName+"/"+"debug.log";
    }
    QFile outFile(app_run_addr);
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&outFile);
    ts << txt << endl;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //初始化qdebug的输出重定向到文件
    qInstallMessageHandler(customMessageHandler);

    Widget w;
    w.show();
    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/xiaolong1126626497/article/details/111571687