log.hpp 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef log_hpp
  2. #define log_hpp
  3. #include <iostream>
  4. #include <fstream>
  5. #include <cstring>
  6. #include <map>
  7. namespace filval::util{
  8. enum LogPriority {
  9. kLogEmergency = 7, // system is unusable
  10. kLogAlert = 6, // action must be taken immediately
  11. kLogCritical = 5, // critical conditions
  12. kLogError = 4, // error conditions
  13. kLogWarning = 3, // warning conditions
  14. kLogNotice = 2, // normal, but significant, condition
  15. kLogInfo = 1, // informational message
  16. kLogDebug = 0 // debug-level message
  17. };
  18. #define CRITICAL(x,y) std::clog << filval::util::LogPriority::kLogCritical << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush; exit(y)
  19. #define ERROR(x) std::clog << filval::util::LogPriority::kLogError << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush
  20. #define WARNING(x) std::clog << filval::util::LogPriority::kLogWarning << x << std::flush
  21. #define INFO(x) std::clog << filval::util::LogPriority::kLogInfo << x << std::flush
  22. #define DEBUG(x) std::clog << filval::util::LogPriority::kLogDebug << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush
  23. /**
  24. * /see http://stackoverflow.com/questions/2638654/redirect-c-stdclog-to-syslog-on-unix
  25. */
  26. std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
  27. class Log : public std::basic_streambuf<char, std::char_traits<char> > {
  28. private:
  29. std::string buffer_;
  30. std::ofstream logfile;
  31. LogPriority priority_curr;
  32. LogPriority priority_set;
  33. std::map<LogPriority,std::string> name_map = {{kLogEmergency, "EMERGENCY"},
  34. {kLogAlert, "ALERT"},
  35. {kLogCritical, "CRITICAL"},
  36. {kLogError, "ERROR"},
  37. {kLogWarning, "WARNING"},
  38. {kLogNotice, "NOTICE"},
  39. {kLogInfo, "INFO"},
  40. {kLogDebug, "DEBUG"}};
  41. friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority){
  42. static_cast<Log *>(os.rdbuf())->priority_curr = log_priority;
  43. return os;
  44. }
  45. protected:
  46. int sync(){
  47. if (buffer_.length()) {
  48. if (priority_curr >= priority_set){
  49. logfile << name_map[priority_curr] << ": " << buffer_ << std::endl << std::flush;
  50. }
  51. buffer_.erase();
  52. /* priority_curr = kLogDebug; // default to debug for each message */
  53. }
  54. return 0;
  55. }
  56. int overflow(int c){
  57. if (c != EOF) {
  58. buffer_ += static_cast<char>(c);
  59. } else {
  60. sync();
  61. }
  62. return c;
  63. }
  64. public:
  65. explicit Log(std::string filename, LogPriority priority)
  66. :logfile(filename, std::ofstream::out){
  67. priority_set = priority;
  68. priority_curr = kLogDebug;
  69. }
  70. };
  71. }
  72. #endif // log_hpp