anjinkristou

Log in Qt

Jun 9th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #ifndef LOG_H
  2. #define LOG_H
  3.  
  4. #include "singleton.h"
  5.  
  6. #include <QTextStream>
  7.  
  8. /*!
  9.  * \brief Provides log
  10.  * \author Etrnls <[email protected]>
  11.  */
  12. class Log : public QObject, public Singleton<Log>
  13. {
  14.     Q_OBJECT
  15. public:
  16.     template <class T>
  17.     Log& operator<<(const T &x)
  18.     {
  19.         stream << ' ' << x;
  20.         return *this;
  21.     }
  22. private:
  23.     QTextStream stream;
  24.  
  25.     Log();
  26.     virtual ~Log();
  27.  
  28.     friend class Singleton<Log>;
  29.     friend Log& log(const QObject *object);
  30. };
  31.  
  32. /*!
  33.  * \brief The global function to retrieve the instance of the Log
  34.  */
  35. Log& log(const QObject *object);
  36.  
  37. #endif
  38. //-------------------------------------
  39. #include "log.h"
  40.  
  41. #include <QFile>
  42. #include <QDir>
  43. #include <QFileInfo>
  44. #include <QMetaClassInfo>
  45. #include <QDateTime>
  46. #include <QCoreApplication>
  47.  
  48. Log::Log()
  49. {
  50.     QFile *file = new QFile(QFileInfo(QDir(QCoreApplication::applicationDirPath()),
  51.                         QLatin1String("log")).absoluteFilePath());
  52.     file->open(QFile::WriteOnly | QFile::Truncate | QFile::Text | QFile::Unbuffered);
  53.     stream.setDevice(file);
  54. }
  55.  
  56. Log::~Log()
  57. {
  58.     delete stream.device();
  59. }
  60.  
  61. Log& log(const QObject *object)
  62. {
  63.     const QMetaObject *metaObject = object->metaObject();
  64.  
  65.     Log::getInstance()->stream << '[' << QDateTime::currentDateTime().toString(Qt::ISODate) << ']'
  66.                 << '[' << metaObject->classInfo(metaObject->indexOfClassInfo("log")).value() << ']';
  67.  
  68.     return *Log::getInstance();
  69. }
Advertisement
Add Comment
Please, Sign In to add comment