Guest User

C++11 fast logging example

a guest
Oct 29th, 2013
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.37 KB | None | 0 0
  1. //
  2. // compile with
  3. // g++ -o log_example main.cpp -pthread -std=c++11 -O4
  4. //
  5.  
  6.  
  7.  
  8. #include <string>
  9. #include <iostream>
  10. #include <iomanip>
  11. #include <sstream>
  12. #include <fstream>
  13. #include <vector>
  14. #include <memory>
  15. #include <future>
  16. #include <thread>
  17. #include <mutex>
  18. #include <sys/time.h>
  19.  
  20. //{ unicode wrappers
  21.  
  22. typedef wchar_t tchar;
  23. typedef wchar_t ttimestr[40];
  24.  
  25. typedef std::wstring        tstring;
  26. typedef std::wostream       tostream;
  27. typedef std::wostringstream tostringstream;
  28. typedef std::wofstream      tofstream;
  29.  
  30. inline static size_t tcstime( tchar* str, size_t count, tchar const* fmt, tm* time ) {
  31.     return wcsftime( str, count, fmt, time );
  32. }
  33.  
  34. //}
  35.  
  36.  
  37. ///////////////////////////////////////////////////////////////////////////////
  38. template <typename T, size_t N> inline size_t _countof(T (&)[N]) { return N; }
  39.  
  40. ///////////////////////////////////////////////////////////////////////////////
  41. class LogMessage {
  42.        
  43.         friend tostream& operator<< ( tostream& os, LogMessage const& lm );
  44.     private:
  45.         tstring         msg;
  46.         struct timeval  time;
  47.  
  48.     public:
  49.         LogMessage( tstring const& str )
  50.             : msg( str ), time()
  51.         {
  52.             gettimeofday( &time, NULL );
  53.         }
  54.         virtual~ LogMessage() {
  55.         }
  56. };
  57.  
  58. ///////////////////////////////////////////////////////////////////////////////
  59. inline tostream& operator<< ( tostream& os, LogMessage const& lm ) {
  60.     struct tm timeSt     = { 0 };
  61.     ttimestr  timeBuffer = { 0 };
  62.    
  63.     if ( tcstime( timeBuffer, _countof(timeBuffer), L"%d.%m.%y %T", localtime_r( &lm.time.tv_sec, &timeSt )))
  64.         os << timeBuffer << L":" << std::setfill(L'0') << std::setw(6) << lm.time.tv_usec;
  65.     else
  66.         os << L"time not recognized";
  67.  
  68.    os << L"\t" << lm.msg << std::endl;
  69.    os.flush();
  70.    return os;
  71. }
  72.  
  73. ///////////////////////////////////////////////////////////////////////////////
  74. class MessagesQueue {
  75.     private:
  76.         typedef std::shared_ptr<LogMessage> MsgObject;
  77.         typedef std::vector<MsgObject> MsgList;
  78.  
  79.     private:
  80.         tostream& output;
  81.        
  82.         std::mutex collector_mutex, printer_mutex, start_mutex;
  83.         MsgList * messagesCollector, * messagesPrinter;
  84.  
  85.     private:
  86.         void start()
  87.         {
  88.             if ( printer_mutex.try_lock())
  89.             {
  90.                 bool nothingToPrint = messagesPrinter->empty();
  91.                 printer_mutex.unlock();
  92.  
  93.                 if ( nothingToPrint )
  94.                 {
  95.                     bool collectedToPrint = false;
  96.                     if ( collector_mutex.try_lock())
  97.                     {
  98.                         collectedToPrint = !messagesCollector->empty();
  99.                         collector_mutex.unlock();
  100.                     }
  101.                    
  102.                     if ( collectedToPrint )
  103.                     {
  104.                         {
  105.                             std::unique_lock<std::mutex> pl(printer_mutex,   std::defer_lock);
  106.                             std::unique_lock<std::mutex> cl(collector_mutex, std::defer_lock);
  107.                            
  108.                             std::lock( pl, cl );
  109.                             std::swap( messagesPrinter, messagesCollector );
  110.                         }
  111.                        
  112.                         std::async( std::launch::async, [&]() {
  113.                             printer_mutex.lock();
  114.                             for ( MsgObject& m: *messagesPrinter) {
  115.                                 output << *(m.get());
  116.                             }
  117.                             messagesPrinter->clear();
  118.                             printer_mutex.unlock();
  119.                         });
  120.                     }
  121.                 }
  122.             }
  123.         }
  124.  
  125.     public:
  126.         MessagesQueue(tostream &os)
  127.             : output(os),
  128.                 messagesCollector( new MsgList()),
  129.                 messagesPrinter( new MsgList())
  130.         {
  131.         }
  132.         virtual ~MessagesQueue() {
  133.             std::unique_lock<std::mutex> pl(printer_mutex,   std::defer_lock);
  134.             std::unique_lock<std::mutex> cl(collector_mutex, std::defer_lock);
  135.             std::unique_lock<std::mutex> sl(start_mutex,     std::defer_lock);
  136.                    
  137.             std::lock( pl, cl, sl );
  138.            
  139.             delete messagesCollector;
  140.             delete messagesPrinter;
  141.         }
  142.  
  143.         void Message( tstring const& a ) {
  144.             {
  145.                 collector_mutex.lock();
  146.                 MsgObject o (new LogMessage( a ));
  147.                 messagesCollector->push_back( o );
  148.                 collector_mutex.unlock();
  149.                
  150.             }
  151.             if (start_mutex.try_lock()) {
  152.                 start();
  153.                 start_mutex.unlock();
  154.             }
  155.         }
  156. };
  157.  
  158.  
  159. ///////////////////////////////////////////////////////////////////////////////
  160. class Widget {
  161.     private:
  162.         tstring const widget_id;
  163.     public:
  164.         Widget( tstring const& id ) : widget_id( id ) {}
  165.         Widget( Widget const& w ) : widget_id( w.widget_id ) {}
  166.        
  167.         const tstring &get_widget_id() const {
  168.             return widget_id;
  169.         }
  170. };
  171.  
  172. ///////////////////////////////////////////////////////////////////////////////
  173. typedef std::vector<Widget> WList;
  174.  
  175. ///////////////////////////////////////////////////////////////////////////////
  176. void f ( bool &stop, WList wl, MessagesQueue& log ) {
  177.    
  178.     while (!stop) {
  179.  
  180.         bool firstNoComma = true;
  181.         tostringstream os;
  182.         os << L"The system detected a Foo event while being in state Bar and keeping track of the folowing Widgets: [";
  183.        
  184.         for ( auto const& i: wl) {
  185.            
  186.             if ( stop ) {
  187.                 break;
  188.             }
  189.            
  190.             if (!firstNoComma) {
  191.                 os << L", ";
  192.             } else {
  193.                 firstNoComma = false;
  194.             }
  195.            
  196.             os << i.get_widget_id();
  197.         }
  198.         os << L"]";
  199.        
  200.         log.Message( os.str());
  201.     }
  202. }
  203.  
  204.  
  205. ///////////////////////////////////////////////////////////////////////////////
  206. ///////////////////////////////////////////////////////////////////////////////
  207. int main(int argc, char** argv) {
  208.  
  209.     tofstream outfile( "output.log", std::ios::out|std::ios::ate );
  210.  
  211.     MessagesQueue log( outfile );
  212.    
  213.     bool threads_stop = false;
  214.  
  215.     Widget th1[] = {
  216.         Widget( L"Widget1" ),
  217.         Widget( L"Widget2" ),
  218.         Widget( L"Widget3" )
  219.     };
  220.     Widget th2[] = {
  221.         Widget( L"Widget4" ),
  222.         Widget( L"Widget5" ),
  223.         Widget( L"Widget6" )
  224.     };
  225.     Widget th3[] = {
  226.         Widget( L"Widget7" ),
  227.         Widget( L"Widget8" ),
  228.         Widget( L"Widget9" )
  229.     };
  230.    
  231.     WList
  232.         thlist1( th1, th1 + _countof(th1)),
  233.         thlist2( th2, th2 + _countof(th2)),
  234.         thlist3( th3, th3 + _countof(th3));
  235.    
  236.     std::thread t1 ( f, std::ref(threads_stop), thlist1, std::ref(log));
  237.     std::thread t2 ( f, std::ref(threads_stop), thlist2, std::ref(log));
  238.     std::thread t3 ( f, std::ref(threads_stop), thlist3, std::ref(log));
  239.    
  240.     {
  241.         std::async( std::launch::async, [&]() {
  242.             std::chrono::seconds dura( 20 );
  243.             std::this_thread::sleep_for( dura );
  244.             threads_stop = true;
  245.         });
  246.     }
  247.    
  248.     t1.join();
  249.     t2.join();
  250.     t3.join();
  251.  
  252.     return 0;
  253. }
Advertisement
Add Comment
Please, Sign In to add comment