Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Sep 7th, 2012  |  syntax: C++  |  size: 1.40 KB  |  views: 28  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <string>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <sstream>
  5. #include <mutex>
  6. #include <ctime>
  7.  
  8. enum class lvl {
  9.         MAX,
  10.         FATAL,
  11.         IMPORTANT,
  12.         ERROR,
  13.         WARNING,
  14.         MESSAGE,
  15.         SPAM,
  16.         MIN
  17. };
  18.  
  19. class log {
  20. public:
  21.         log(lvl level = lvl::MESSAGE) {
  22.                 this->level = level;
  23.         }
  24.  
  25.         /*
  26.          * destroys the logline object. this destructor will output the
  27.          * logline's accumulated content, in a thread-safe way.
  28.          */
  29.         ~log() {
  30.                 //thread-safety etc
  31.                 std::unique_lock<mutex> lock(globalmutex);
  32.                 //in this simplified class, we just output the whole line to
  33.                 //stdout, but in the real version there is a log of
  34.                 //manipulation of global data structures happening right here.
  35.                 if(level <  lvl::WARNING) {
  36.                         cout << '[' << time(NULL) << "] ";
  37.                         cout << sstr.str() << endl;
  38.                 }
  39.         }
  40.  
  41.         //for writing normal types
  42.         template<typename T>
  43.         log &operator<<(T x) {
  44.                 sstr << x;
  45.                 return *this;
  46.         }
  47.  
  48.         //for writing function pointers, such as endl or setw(5).
  49.         template<typename T>
  50.         log &operator<<(T &(*x)(T &)) {
  51.                 sstr << x;
  52.                 return *this;
  53.         }
  54.  
  55. private:
  56.         //this particular log line's level.
  57.         lvl level;
  58.         //accumulates all input.
  59.         std::stringstream sstr;
  60.         //to ensure thread-safety
  61.         static std::mutex globalmutex;
  62. };
  63.  
  64. int main() {
  65.         log(lvl::SPAM) << "main method initialized";
  66.         log(lvl::MESSAGE) << "the time is: " << time(NULL);
  67.         log(lvl::SPAM) << "main method de-initializing";
  68. }
clone this paste RAW Paste Data