I’m writing a c++ shared library that is intended to be used by other library or executable. What is the best way to add a generic logging in my library? Ideally I’d like to adapt my library to logging functionality chosen by the library’s user.
Suppose i have a class in my library
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 ? */
}
I don’t want to make my library tied to any log4XXX specific API.
You can provide a callback mechanism to allow the library’s user to provide your library with an adapter into their logging.
I.e., in your library provide an abstract logging interface class, e.g.:
and a class to regster a Logger with:
Your library then logs with something like:
The application using your library should provide an implementation of Logger (i.e. a concrete subclass) and register it with your Log class. Their Logger impl will implement logging as they see fit.
This allows your library to be used by applications which use different logging libraries.
Note the above code is basic and untested. In practice you may want to change the log methods to include a logging level parameter, etc.