QTアプリケーションプログラミング:ログファイルへのQDebug出力リダイレクト

1.環境紹介

オペレーティングシステムの紹介: win1064ビット

QTバージョン:  5.12.6

2.機能紹介

ログファイルへのQDebug出力リダイレクトを初期化します。リダイレクト後、プログラムのqDebug()<< "xxx"によって出力されたデータはログファイルに保存されます。プログラムがリリースされた後、ログファイルを表示すると便利です。プログラムの実行を理解する。

3、サンプルコード

#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