title: Custom and Default Message Handler in Qt
body: <p>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?</p>
  
  <p>Header:</p>
  
  <pre><code>#ifndef QLOGGER_H
  #define QLOGGER_H
  
  #include &lt;QtCore/QObject&gt;
  #include &lt;QtCore/QFile&gt;
  #include &lt;QtCore/QDateTime&gt;
  
  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
  </code></pre>
  
  <p>Source:</p>
  
  <pre><code>#include &lt;QTextStream&gt;
  #include &lt;QDateTime&gt;
  #include &lt;QDir&gt;
  #include &lt;iostream&gt;
  
  #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(&amp;logFile);
  
          switch (type){
                   case QtDebugMsg:
                       finish();
                       qDebug(msg);
                       break;
                   case QtWarningMsg:
                       streamer &lt;&lt; QDateTime::currentDateTime().toString() &lt;&lt;" Warning: " &lt;&lt; msg &lt;&lt;  "\n";
                       finish();
                       qWarning(msg);
                       break;
                   case QtCriticalMsg:
                       streamer &lt;&lt; QDateTime::currentDateTime().toString() &lt;&lt;" Critical: " &lt;&lt; msg &lt;&lt;  "\n";
                       finish();
                       qCritical(msg);
                       break;
                   case QtFatalMsg:
                       streamer &lt;&lt; QDateTime::currentDateTime().toString() &lt;&lt;" Fatal: " &lt;&lt; msg &lt;&lt;  "\n";
                       finish();
                       qFatal(msg);
                       break;
          }
          logFile.close();
      }
      start();
  }
  </code></pre>