创建单件模式的Logger类

《C++高级编程》第二十六章的一个例子。

/**
 * Logger.h
 *
 * Definition of a singleton logger class, implemented with static methods
 */
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

class Logger
{
public:
 static const std::string kLogLevelDebug;
 static const std::string kLogLevelInfo;
 static const std::string kLogLevelError;

 // Return a reference to the singleton logger object
 static Logger& instance();
 // Log a single message at the given log level
 void log(const std::string& inMessage, const std::string& inLogLevel);
 // Log a vector of messages at the given log level
 void log(const std::vector<std::string>& inMessage, const std::string& inLogLevel);

protected:
 // static variable for the one-and-only instance
 static Logger sInstance;
 // Constant for the filename
 static const char* const kLogFileName;
 // Data member for the output stream
 std::ofstream mOutputStream;

private:
 // 关键:私有的构造函数,不能实例化,因为实例化时类外部无法访问其内部的私有的构造函数
 Logger(void);
 ~Logger(void);
};

 

/**
 * Logger.cpp
 * 
 * Implementation of a singleton logger class
 */
#include "Logger.h"
#include <string>
using namespace std;

const string Logger::kLogLevelDebug = "DEBUG";
const string Logger::kLogLevelInfo = "INFO";
const string Logger::kLogLevelError = "Error";

const char* const Logger::kLogFileName = "log.out";

// The static instance will be construct when the program starts and destructed when it ends.
Logger Logger::sInstance;

Logger::Logger(void)
{
 mOutputStream.open(kLogFileName, ios_base::app);
 if (!(mOutputStream.good())) {
  cerr << "Unable to initialize the Logger!" << endl;
 }
}

Logger::~Logger(void)
{
 mOutputStream.close();
}

Logger& Logger::instance()
{
 return sInstance;
}

void Logger::log(const std::string& inMessage, const std::string& inLogLevel)
{
 mOutputStream << inLogLevel << ":" << inMessage << endl;
}

void Logger::log(const std::vector<std::string>& inMessage, const std::string& inLogLevel)
{
 for (size_t i=0; i<inMessage.size(); i++) {
  log(inMessage[i], inLogLevel);
 }
}

 

// TestTrueSingletonLogger.cpp
#include "Logger.h"
#include <vector>
#include <string>

int main(int argc, char **argv)
{
 Logger::instance().log("test message", Logger::kLogLevelDebug);
 vector<string> items;
 items.push_back("item1");
 items.push_back("item2");
 Logger::instance().log(items, Logger::kLogLevelError);

 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值