源代码在VC++ 6.0通过编译
1 //SingletonHeader.h 2 #include <IOSTREAM> 3 #include <FSTREAM> 4 #include <VECTOR> 5 6 class Logger{ 7 public: 8 static const std::string kLogLevelDebug; 9 static const std::string kLogLevelInfo; 10 static const std::string kLogLevelError; 11 12 static Logger& instance(); 13 14 //Logs a single message at the given log level 15 void log(const std::string& inMessage, 16 const std::string& inLogLevel); 17 //Logs a vector of message at the given log level 18 void log(const std::vector<std::string>& inMessages, 19 const std::string& inLogLevel); 20 21 22 protected: 23 static Logger sInstance; 24 static const char* const kLogFileName; 25 std::ofstream mOutputStream; 26 27 private: 28 Logger(); 29 virtual ~Logger(); 30 };
1 //SingletonHeader.cpp 2 #include "SingletonHeader.h" 3 #include <STRING> 4 using namespace std; 5 6 const string Logger::kLogLevelDebug = "DEBUG"; 7 const string Logger::kLogLevelInfo = "INFO"; 8 const string Logger::kLogLevelError = "ERROR"; 9 10 const char* const Logger::kLogFileName = "log.out"; 11 12 Logger Logger::sInstance; 13 14 Logger& Logger::instance() 15 { 16 return sInstance; 17 } 18 19 Logger::Logger() 20 { 21 mOutputStream.open(kLogFileName,ios_base::app); 22 if (!mOutputStream.good()) 23 { 24 cerr<<"Unable to initialize the Logger!"<<endl; 25 } 26 } 27 28 Logger::~Logger() 29 { 30 mOutputStream.close(); 31 } 32 33 34 void Logger::log(const string& inMessage, const string& inLogLevel) 35 { 36 mOutputStream << inLogLevel << ":" << inMessage << endl; 37 } 38 39 void Logger::log(const vector<string>& inMessages, const string& inLogLevel) 40 { 41 for (size_t i=0;i<inMessages.size();i++) 42 { 43 log(inMessages[i],inLogLevel); 44 } 45 } 46 47 int main(int argc, char **argv) 48 { 49 Logger::instance().log("test message",Logger::kLogLevelDebug); 50 vector<string> items; 51 52 items.push_back("item1"); 53 items.push_back("item2"); 54 55 Logger::instance().log(items,Logger::kLogLevelError); 56 57 return 0; 58 }