开发者

Custom and Default Message Handler in Qt

I want to use default Qt message handler while logging messages to a log file except qDebug. Here my solution, do you have any suggestion or what are the possible problems with this implementation?

Header:

#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::cur开发者_开发问答rentDateTime().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();
}


Afaik this is not going to work, you are implementing the message handler function as a member function to a an object the signature of the function that qInstallMessageHandler takes is void myMsgHandler(QtMsgType, const char *);

You can either implement the function as a plain freestanding function or use a singleton with a static accessor e.g.

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

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

this gives you a function to use for qInstallMsgHandler and an object to wrap the logging

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜