Custom and mail message handler in Qt

I want to use the default Qt message handler when writing messages to a log file other than qDebug. Here is my decision, do you have any suggestions or any possible problems with this implementation?

Title:

#ifndef QLOGGER_H
#define QLOGGER_H

#include <QtCore/QObject>
#include <QtCore/QFile>
#include <QtCore/QDateTime>

class QLogger : public QObject
{
Q_OBJECT

public:
    QLogger();
   ~QLogger();

    static void start();
    static void finish();
    static QString filename;

private:
    static void myloggerfunction(QtMsgType type, const char *msg);

};

#endif // QLOGGER_H

Source:

#include <QTextStream>
#include <QDateTime>
#include <QDir>
#include <iostream>

#include "qlogger.h"

using namespace std;

QString QLogger::filename=QString("log.txt");

QLogger::QLogger()
{
}

QLogger::~QLogger()
{
}

void QLogger::start()
{
    qInstallMsgHandler(myloggerfunction);
}

void QLogger::finish()
{
    qInstallMsgHandler(0);
}

void QLogger::myloggerfunction(QtMsgType type, const char *msg)
{
    QDir dir;
    dir.cd("LOG");

    QFile logFile(filename);

    if (logFile.open(QIODevice::Append | QIODevice::Text))
    {
        QTextStream streamer(&logFile);

        switch (type){
                 case QtDebugMsg:
                     finish();
                     qDebug(msg);
                     break;
                 case QtWarningMsg:
                     streamer << QDateTime::currentDateTime().toString() <<" Warning: " << msg <<  "\n";
                     finish();
                     qWarning(msg);
                     break;
                 case QtCriticalMsg:
                     streamer << QDateTime::currentDateTime().toString() <<" Critical: " << msg <<  "\n";
                     finish();
                     qCritical(msg);
                     break;
                 case QtFatalMsg:
                     streamer << QDateTime::currentDateTime().toString() <<" Fatal: " << msg <<  "\n";
                     finish();
                     qFatal(msg);
                     break;
        }
        logFile.close();
    }
    start();
}
+5
source share
2 answers

Afaik this will not work, you implement the message handler function as a member function for the object, the signature of the function that it qInstallMessageHandleraccepts isvoid myMsgHandler(QtMsgType, const char *);

You can either implement the function as a regular stand-alone function, or use a singleton with a static accessory, for example.

void msgHandler(QtMsgType type, const char * msg)
{
   Logger::instance()->handleMessage(type,msg);
}

class Logger
{
  static Logger* instance() {... }
  void handleMessage(QtMsgType type, const char* msg) { ... }
}

qInstallMsgHandler

+5

, , , 2 :

1. QtMessageHandler()

void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);

2. qInstallMessageHandler(), QtMessageHandler

0

All Articles