123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- #ifndef log_hpp
- #define log_hpp
- #include <iostream>
- #include <fstream>
- #include <cstring>
- #include <map>
- namespace fv::util{
- enum LogPriority {
- kLogEmergency = 7,
- kLogAlert = 6,
- kLogCritical = 5,
- kLogError = 4,
- kLogWarning = 3,
- kLogNotice = 2,
- kLogInfo = 1,
- kLogDebug = 0
- };
- #define CRITICAL(x,y) std::clog << fv::util::LogPriority::kLogCritical << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush; std::cout << "Errors encountered! See log file for details."<<std::endl;exit(y)
- #define ERROR(x) std::clog << fv::util::LogPriority::kLogError << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush
- #define WARNING(x) std::clog << fv::util::LogPriority::kLogWarning << x << std::flush
- #define INFO(x) std::clog << fv::util::LogPriority::kLogInfo << x << std::flush
- #define DEBUG(x) std::clog << fv::util::LogPriority::kLogDebug << __FILE__ << "@L" << __LINE__ << " :: " << x << std::flush
- std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
- class Log : public std::basic_streambuf<char, std::char_traits<char> > {
- private:
- std::string buffer_;
- std::ofstream logfile;
- LogPriority priority_curr;
- LogPriority priority_set;
- inline static Log* singleton = nullptr;
- const std::map<LogPriority,std::string> name_map = {{kLogEmergency, "EMERGENCY"},
- {kLogAlert, "ALERT"},
- {kLogCritical, "CRITICAL"},
- {kLogError, "ERROR"},
- {kLogWarning, "WARNING"},
- {kLogNotice, "NOTICE"},
- {kLogInfo, "INFO"},
- {kLogDebug, "DEBUG"}};
- friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority){
- static_cast<Log *>(os.rdbuf())->priority_curr = log_priority;
- return os;
- }
- protected:
- int sync(){
- if (buffer_.length()) {
- if (priority_curr >= priority_set){
- logfile << name_map.at(priority_curr) << ": " << buffer_ << std::endl << std::flush;
- }
- buffer_.erase();
-
- }
- return 0;
- }
- int overflow(int c){
- if (c != EOF) {
- buffer_ += static_cast<char>(c);
- } else {
- sync();
- }
- return c;
- }
- public:
- explicit Log(std::string filename, LogPriority priority)
- :logfile(filename, std::ofstream::out){
- priority_set = priority;
- priority_curr = kLogDebug;
- }
- static Log& init_logger(std::string filename, LogPriority priority){
- if (singleton == nullptr){
- singleton = new Log(filename, priority);
- std::cout << "Writing log data to " << filename << std::endl;
- std::clog.rdbuf(singleton);
- }
- return *singleton;
- }
- };
- }
- #endif
|