00001
00002
00003 #include <string>
00004 #include <iostream>
00005 #include <ctime>
00006 using namespace std;
00007
00008
00009 class Log {
00010
00011 public:
00012 enum Level {
00013 TRACE = 0, DEBUG = 10, INFO = 20, WARN = 30, ERROR = 40
00014 };
00015
00016 public:
00017 Log(const string& name)
00018 : _name(name), _level(INFO), _nostream(new ostream(0)), _writeTime(true) { }
00019
00020 Log(const string& name, const Level& level)
00021 : _name(name), _level(level), _nostream(new ostream(0)), _writeTime(true) { }
00022
00023 public:
00024 static Log& getLog(const string& name) {
00025 return *(new Log(name));
00026 }
00027
00028 static Log& getLog(const string& name, const Level& level) {
00029 return *(new Log(name, level));
00030 }
00031
00032 public:
00033 Level getLevel() const {
00034 return _level;
00035 }
00036
00037 Log& setLevel(const Level& level) {
00038 _level = level;
00039 return *this;
00040 }
00041
00042 static string getLevelName(const Level& level) {
00043 switch(level) {
00044 case TRACE:
00045 return "TRACE";
00046 case DEBUG:
00047 return "DEBUG";
00048 case INFO:
00049 return "INFO";
00050 case WARN:
00051 return "WARN";
00052 case ERROR:
00053 return "ERROR";
00054 }
00055 }
00056
00057 string getName() const {
00058 return _name;
00059 }
00060
00061 Log& setName(const string& name) {
00062 _name = name;
00063 return *this;
00064 }
00065
00066 bool writeTime() const {
00067 return _writeTime;
00068 }
00069
00070 Log& writeTime(const bool writeTime) {
00071 _writeTime = writeTime;
00072 return *this;
00073 }
00074
00075 bool isActive(const Level& level) const {
00076 return (level >= _level);
00077 }
00078
00079 private:
00080 string _name;
00081
00082 Level _level;
00083
00084 bool _writeTime;
00085
00086 ostream* const _nostream;
00087
00088 public:
00089 friend ostream& operator<<(Log& log, const Level& level);
00090
00091 };
00092
00093
00094 ostream& operator<<(Log& log, const Log::Level& level) {
00095 if (log.isActive(level)) {
00096 time_t rawtime;
00097 time(&rawtime);
00098 char* timestr = ctime(&rawtime);
00099 timestr[24] = ' ';
00100
00101 cout << Log::getLevelName(level) << " ";
00102 cout << log.getName() << ": ";
00103 if (log.writeTime()) {
00104 cout << timestr << " ";
00105 }
00106 return cout;
00107 } else {
00108 return *(log._nostream);
00109 }
00110 }
00111
00112
00113 int main() {
00114 Log log = Log::getLog("foo");
00115 log << Log::INFO << "hello" << endl;
00116 log << Log::DEBUG << "hi" << endl;
00117 log.setLevel(Log::DEBUG);
00118 log << Log::WARN << "hola" << endl;
00119 log << Log::DEBUG << "hey" << endl;
00120 return EXIT_SUCCESS;
00121 }