/*=================================================================
*注意:
* 在接口与数据的安排上,是先接口后数据,这样体现了以行为为中心
* 但是有一个前提就是,无论如何先将构造函数和析构函数摆在最前面
* 因为构造函数和析构函数首先决定了这个类的性质,比如说,
* 带虚析构函数的一般是用来做基类,构造函数不是public的,说明设计师
* 不想实例化该类
*一般的结构为:
* 构造函数
* 析构函数
* public函数
* protected函数
* private函数
* public变量
* protectd变量
* private变量
*
* 本实例是用静态类实现singleton单例模式
*=================================================================*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class Logger
{
private:
Logger(){}
public:
//logs a single message at the given log level
static void log(const string& strMessage, const string& strLogLevel);
//logs a vector of messages at the given log level
static void log(const vector<string>& strMessages, const string& strLogLevel);
//Closes the log file
static void teardown(void);
protected:
static void init(void);
public:
static const string m_strLogLevelDebug;
static const string m_strLogLevelInfo;
static const string m_strLogLevelError;
protected:
static const char* const m_szLogFileName;
static bool sInitialized;
static ofstream sOutputStream;
}
#include "logger.h"
using namespace std;
const string Logger::m_strLogLevelDebug = "DEBUG";
const string Logger::m_strLogLevelInfo = "INFO";
const string Logger::m_strLogLevelError = "ERROR";
const char* const Logger::m_szLogFileName = "log.out";
bool Logger::sInitialized = false;
ofstream Logger::sOutputStream;
void Logger::log(const string& strMessage,const string& strLogLevel)
{
if(!sInitialized)
{
init();
}
sOutputStream << strLogLevel<<":"<<strMessage<<endl;
}
void Logger::log(const vector<string>& strMessages,const string& strLogLevel)
{
for(size_t i = 0; i < strMessages.size(); ++i)
{
log(strMessages[i],strLogLevel);
}
}
void Logger::teardown(void)
{
if(sInitialized)
{
sOutputStream.close();
sInitialized = false;
}
}
void Logger::init(void)
{
if( !sInitialized )
{
sOutputStream.open(szLogFileName,ios_base::app);
if( !sOutputStream.good() )
{
cerr<<"Unable to initialize the logger"<<endl;
return;
}
sInitialized = true;
}
}
int main(int argc, char** argv)
{
Logger::log("test message", Logger::kLogLevelDebug);
vector<string> items;
items.push_back("item1");
items.push_back("item2");
Logger::log(items, Logger::kLogLevelError);
Logger::teardown();
}