chx4

幸福是什么?自我欣赏和东游西荡!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

The tip of today does not represents a general output for the application state in real time, since QDebug only works in debug compilatos.

General usage

Some times we prefer to analyse the our application debug messages in a separated file. It is useful when we want to work with Qt-Creator in full code window and we have two monitors (one for coding and another for application execution and debug file). To redirect the output we have to type in Qt 5.1:

void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
   Q_UNUSED(context);
 
   QString dt = QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss");
   QString txt = QString("[%1] ").arg(dt);
 
   switch (type)
   {
      case QtDebugMsg:
         txt += QString("{Debug} \t\t %1").arg(msg);
         break;
      case QtWarningMsg:
         txt += QString("{Warning} \t %1").arg(msg);
         break;
      case QtCriticalMsg:
         txt += QString("{Critical} \t %1").arg(msg);
         break;
      case QtFatalMsg:
         txt += QString("{Fatal} \t\t %1").arg(msg);
         abort();
         break;
   }
 
   QFile outFile("LogFile.log");
   outFile.open(QIODevice::WriteOnly | QIODevice::Append);
 
   QTextStream textStream(&outFile);
   textStream << txt << endl;
}

 

 

Then, in main function we have to add the following line:

qInstallMessageHandler(customMessageHandler);

 

 

There are two small changes to run this code in Qt 4:

    1. Change the parameters in name function: 
      void customMessageHandler(QtMsgType type, const char *msg)

       

    2. Change the name of the function called:
      qInstallMsgHandler(customMessageHandler);

       

 

Redirecting QDebug with custom class

If we want to redirect the output of our custom class to QDebug, it is necessary to declare the operator << of QDebug type as a friend method:

friend QDebug operator << (QDebug d, const Protocol &p);

 

posted on 2013-08-09 12:23  chx4  阅读(400)  评论(0编辑  收藏  举报