8 c++ logging shared-libraries
我正在编写一个c ++共享库,供其他库或可执行文件使用.在我的库中添加通用日志记录的最佳方法是什么?理想情况下,我想使我的库适应库用户选择的日志记录功能.假设我的图书馆里有一堂课
class A {
public:
void method(string param1, int param2);
}
void A::method(string param1, int param2){
/* i want to log values of param1 and param2,
but actual logging method must be defined outside of my library.
Maybe some kind of macro should help here. */
/*e.g.*/ GENERICLOG_DEBUG("param1=" + param1+ " param2="+param1);
/*if so, what that macro body should look like ? */
}
Run Code Online (Sandbox Code Playgroud)
我不想让我的库绑定到任何log4XXX特定的API.
jon*_*son 10
您可以提供回调机制,以允许库的用户向您的库提供适配器到他们的日志记录中.
即,在您的库中提供抽象日志记录接口类,例如:
class Logger
{
public:
virtual ~Logger () {}
virtual void log (const std::string& message) = 0;
};
Run Code Online (Sandbox Code Playgroud)
和一个用Logster注册Logger的类:
class Log
{
private:
static Logger* logger_;
public:
static void registerLogger (Logger& logger)
{ logger_ = &logger; }
static void log (const std::string& message)
{ if (logger_ != 0) logger_->log (message); }
};
Run Code Online (Sandbox Code Playgroud)
然后你的图书馆会记录如下:
Log::log ("My log message");
Run Code Online (Sandbox Code Playgroud)
使用您的库的应用程序应该提供Logger的实现(即具体的子类)并将其注册到您的Log类.他们的Logger impl将根据需要实施日志记录.
这允许您的库由使用不同日志记录库的应用程序使用.
请注意,上面的代码是基本的,未经测试.实际上,您可能希望更改日志方法以包括日志记录级别参数等.