Suppose I have a logger function class implementation which provides me four public functions:
class Logger
{
public:
error(const string& caller, const string& msg);
warn(const string& caller, const string& msg);
info(const string& caller, const string& msg);
debug(const string& caller, const string& msg);
};
What this class does is basically logging to a file and printing depending on the selected log level like this: cout << "[" << caller << "]: " << msg << endl
. I want to have only one instance of this class and pass that instance to multiple different classes (dependency injection) and depending on where I use this instance I change the 'caller' argument to e.g. 'Foo' or 'Bar'.
class Foo
{
public:
Foo(Logger* log) { log->info("Foo", "Hello"); };
};
class Bar
{
Bar(Logger* log) { log->info("Bar", "Hello"); };
}
Now my question is if there is a way to 'automatically' fill the first argument to avoid having to provide the argument every time I want to log something. What came to my mind first was inhertance and then overloading the functions but that creates more objects of the class of which I only want to have one instance of. Another idea was to define new functions for the other classes which take just the message argument and then call the logger function with the added caller argument. I feel like there has to be a smarter way to do this.