关于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.

发布了87 篇原创文章 · 获赞 64 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/wqfhenanxc/article/details/89556411