QT output information directed to the specified path output

The qInstallMessageHandler (outputMessage) was added to the main () function

 

#include "mainwindow.h"
#include <QApplication>
#include <QDateTime>
#include <QFile>
#include <QMutex>
#include <QTextStream>
#include <QDebug>

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
   static QMutex mutex;
   mutex.lock();

   QString text;
   switch(type)
   {
   case QtDebugMsg:
       text = QString("Debug:");
       break;

   case QtWarningMsg:
       text = QString("Warning:");
       break;

   case QtCriticalMsg:
       text = QString("Critical:");
       break;

   case QtFatalMsg:
       text = QString("Fatal:");
   }

//    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
   QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
   QString current_date = QString("(%1)").arg(current_date_time);
   QString message = QString("%1 %2").arg(current_date).arg(msg);

   QFile file("test_log.txt");
   file.open(QIODevice::WriteOnly | QIODevice::Append);
   QTextStream text_stream(&file);
   text_stream << message << "\r\n";
   file.flush();
   file.close();

   mutex.unlock();

}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(outputMessage);
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Reference: https://blog.csdn.net/lab331252153/article/details/77968455

Published 110 original articles · won praise 2 · Views 3747

Guess you like

Origin blog.csdn.net/qq_40041064/article/details/105047055