关于c++中如何使用Logger的争论

c++中记录log的几个方法:

1. 用一个global的logger

2. 用一个singleton

3. logger作为参数,为需要打印log的类或函数传递logger reference作为参数

 

在这个stackoverflow的讨论中有另外两个方案:

https://stackoverflow.com/questions/5877779/c-logger-class-without-globals-or-singletons-or-passing-it-to-every-method

方案1:使用getLogger

I would imagine you could do something similar to what is done in Java with the Log4j package (and is probably done with the Log4c version of it):

Have a static method which can return multiple logger instances:

Logger someLogger = Logger.getLogger("logger.name");

The getLogger() method isn't returning a singleton object. It's returning the named logger (creating it if necessary). Logger is just an interface (in C++ it could be a totally abstract class) -- the caller doesn't need to know the actual types of the Logger objects being created.

You could continue to mimic Log4j and have an overload of getLogger() that also takes a factory object:

Logger someLogger = Logger.getLogger("logger.name", factory);

That call would use factory to build the logger instance, giving you more control over what underlying Logger objects were being created, likely helping your mocking.

So there's no need to pass anything into the constructors, methods, etc. of your own code. You just grab the desired named Logger when you need it and log to it. Depending on the thread safety of the logging code you write, you could have what getLogger() returns be a static member of your class so you'd only have to call getLogger() once per class.

 

方案2:

A class with some static methods。

class Logger
{
public:
  static void record(string message)
  {
    static ofstream fout("log");
    fout << message << endl;;
  }
  ...
};

...

void someOtherFunctionSomewhere()
{
  Logger::record("some string");
  ...
}

No Singleton, no global variable, but any code that can see Logger.h can call the member function, and if all of the public member functions return void, it's trivially easy to stub out for testing.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值