Qt - save QDebug information to a file

Qt's qdebug can easily output the LOG information, but sometimes we need to save the LOG information locally for later viewing. For example, we need to use Qt opened software, and then package and publish it. At this time, we need to save the useful LOG information locally. If there is any problem in the use of the software, we can based on the saved LOG information, Bug appears in the location software.
Don't talk much, just go to Code. There is Code and there is truth.

#include <QDir>
#include <QTextStream>
#include "iostream"
#include <QDateTime>
#include "QDebug"
using namespace std;
void setDebugOutput(const QString &rawTargetFilePath_, const bool &argDateFlag_)
{
    static QString rawTargetFilePath;
    static bool argDateFlag;
    rawTargetFilePath = rawTargetFilePath_;
    argDateFlag = argDateFlag_;
    class HelperClass
    {
    public:
        static void messageHandler(QtMsgType type, const QMessageLogContext &, const QString &message_)
        {
            QString message;

            switch ( type )
            {
                case QtDebugMsg:
                {
                    message = message_;
                    break;
                }
                case QtWarningMsg:
                {
                    message.append("Warning: ");
                    message.append(message_);
                    break;
                }
                case QtCriticalMsg:
                {
                    message.append("Critical: ");
                    message.append(message_);
                    break;
                }
                case QtFatalMsg:
                {
                    message.append("Fatal: ");
                    message.append(message_);
                    break;
                }
                default: { break; }
            }

            QString currentTargetFilePath;
            currentTargetFilePath = rawTargetFilePath;
            if ( !QFileInfo::exists( currentTargetFilePath ) )
            {
                QDir().mkpath( QFileInfo( currentTargetFilePath ).path() );
            }

            QFile file( currentTargetFilePath );
            file.open( QIODevice::WriteOnly | QIODevice::Append );

            QTextStream textStream( &file );
            textStream << QDateTime::currentDateTime().toString( "yyyy-MM-dd hh:mm:ss:zzz" ) << ": " << message << endl;
        }
    };
    qInstallMessageHandler( HelperClass::messageHandler );
}

  setDebugOutput(const QString &rawTargetFilePath_ , const bool &argDateFlag_ )The parameters are as follows:

  • rawTargetFilePath_ Save path for LOG.
  • argDateFlag_ Set it to false.

Tags: Qt

Posted on Mon, 25 May 2020 12:41:10 -0400 by SpectralDesign.Net