bremenpl

Untitled

Jun 26th, 2015
17
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * CLogger.h
  3.  *
  4.  *  Created on: 25 cze 2015
  5.  *      Author: lukasz
  6.  */
  7.  
  8. #ifndef CLOGGER_H_
  9. #define CLOGGER_H_
  10.  
  11. #include <iostream>
  12. #include <deque>
  13. #include <string>
  14. #include <mutex>
  15. #include <condition_variable>
  16. #include <pthread.h>
  17. #include <ostream>
  18. #include <fstream>
  19. #include <sstream>
  20. #include <ctime>
  21.  
  22. using namespace std;
  23.  
  24. class CLogger
  25. {
  26. public:
  27.     enum class ElogLevel { eNone = 0, eError, eWarning, eInfo, eDebug };
  28.  
  29.     typedef struct
  30.     {
  31.         string logString;
  32.         ElogLevel logLevel;
  33.     } logline_t;
  34.  
  35.     static CLogger* instance(ElogLevel ll = ElogLevel::eError);
  36.  
  37.     bool startLog(string fileName, bool verbose);
  38.     logline_t pop_front();
  39.     void push_back(logline_t s);
  40.     void setLogLevel(ElogLevel ll);
  41.     void stopLog();
  42.  
  43.     template<typename T>
  44.     CLogger& operator<<(const T& t)
  45.     {
  46.         if (((int)m_logLine.logLevel <= (int)m_userDefinedLogLevel) && m_logStarted)
  47.         {
  48.             ostringstream stream;
  49.             stream << t;
  50.             m_logLine.logString += stream.str();
  51.  
  52.             if (stream.str().find("\n") != string::npos)
  53.             {
  54.                 push_back(m_logLine);
  55.                 m_logLine.logString.clear();
  56.             }
  57.         }
  58.  
  59.         return *this;
  60.     }
  61.  
  62. protected:
  63.     virtual void threadLoop();
  64.  
  65. private:
  66.     CLogger() {};                               // Private so that it can  not be called
  67.     CLogger(CLogger const&) {};                 // copy constructor is private
  68.     CLogger& operator= (CLogger const&) {};     // assignment operator is private
  69.  
  70.     static CLogger* mp_instance;
  71.     bool m_logStarted;
  72.     logline_t m_logLine;
  73.     ElogLevel m_userDefinedLogLevel;
  74.     ofstream m_logFileStream;
  75.     bool m_verbose;
  76.     bool m_finishLog;
  77.  
  78.     static void * threadHelper(void* handler)
  79.     {
  80.         ((CLogger*)handler)->threadLoop();
  81.         return NULL;
  82.     }
  83.  
  84.     deque<logline_t> m_data;
  85.     mutex m_mutex;
  86.     condition_variable m_cv;
  87.     pthread_t   m_thread;
  88. };
  89.  
  90. #endif /* CLOGGER_H_ */
RAW Paste Data