Qt QML Log Redirection to file

Info Thread
By -
0

 QML Debug - Visual Studio Marketplace

Qt redirects debug information output to (stdout, stderr, files, etc.)

The debugging information here is the output of qDebug(), qWarning(), qCritical(), qFatal(). By registering a callback function: 

qInstallMessageHandler(Qt5.x version used Api);

You can redirect (intercept) the debugging information.

The Qt5.x version callback function can realize the output type and information, and the output can be redirected to a file, stdout (screen) or stderr by changing the value of the output variable.

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QCoreApplication>
#include <QDebug>
#include <stdio.h>
#include <stdlib.h>
#define DEBUG_MODE 1

FILE *output = NULL;
void outputRedirection(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
    case QtDebugMsg:
        fprintf(output, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtInfoMsg:
        fprintf(output, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtWarningMsg:
        fprintf(output, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtCriticalMsg:
        fprintf(output, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtFatalMsg:
        fprintf(output, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        abort();
    }
}

int main(int argc, char **argv) {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif
QGuiApplication app(argc, argv);
#ifdef DEBUG_MODE output = fopen("output.txt", "a"); //redirected to file #else //output = stdout; // redirected to printout output = stderr; // Redirection and error output if(output) fclose(output); #endif qInstallMessageHandler(outputRedirection);
QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }

 

Generally, the application uses this function after the release version is released, and also implements functions such as logging.



Tags:

Post a Comment

0Comments

Post a Comment (0)