log.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #ifndef log_hpp
  2. #define log_hpp
  3. #include <iostream>
  4. #include <fstream>
  5. #include <cstring>
  6. #define LOG_EMERG 0
  7. #define LOG_ALERT 1
  8. #define LOG_CRIT 2
  9. #define LOG_ERR 3
  10. #define LOG_WARNING 4
  11. #define LOG_NOTICE 5
  12. #define LOG_INFO 6
  13. #define LOG_DEBUG 7
  14. enum LogPriority {
  15. kLogEmerg = LOG_EMERG, // system is unusable
  16. kLogAlert = LOG_ALERT, // action must be taken immediately
  17. kLogCrit = LOG_CRIT, // critical conditions
  18. kLogErr = LOG_ERR, // error conditions
  19. kLogWarning = LOG_WARNING, // warning conditions
  20. kLogNotice = LOG_NOTICE, // normal, but significant, condition
  21. kLogInfo = LOG_INFO, // informational message
  22. kLogDebug = LOG_DEBUG // debug-level message
  23. };
  24. /**
  25. * /see http://stackoverflow.com/questions/2638654/redirect-c-stdclog-to-syslog-on-unix
  26. */
  27. class Log : public std::basic_streambuf<char, std::char_traits<char> > {
  28. private:
  29. friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority){
  30. static_cast<Log *>(os.rdbuf())->priority_ = (int)log_priority;
  31. return os;
  32. }
  33. std::string buffer_;
  34. std::ofstream logfile;
  35. int priority_;
  36. protected:
  37. int sync(){
  38. if (buffer_.length()) {
  39. /* syslog(priority_, buffer_.c_str()); */
  40. logfile << buffer_ << std::endl;
  41. buffer_.erase();
  42. priority_ = LOG_DEBUG; // default to debug for each message
  43. }
  44. return 0;
  45. }
  46. int overflow(int c){
  47. if (c != EOF) {
  48. buffer_ += static_cast<char>(c);
  49. } else {
  50. sync();
  51. }
  52. return c;
  53. }
  54. public:
  55. explicit Log(std::string filename)
  56. :logfile(filename, std::ofstream::out){
  57. priority_ = LOG_DEBUG;
  58. }
  59. };
  60. #endif // log_hpp