Cornel Verster
Cornel Verster

Reputation: 1783

Interface vs. Individual Loggers

I want to implement loggers in a C++ project that I am working on. I am wondering whether it would be better to implement a logger within each class individually, or to have a single logging interface and instantiate an instance of it in each class using the log4cxx libraries. I have a few loggers I would like to implement that would log events in existing classes.

In using a logging interface, I mean:

class Logger
{
private:
    log4cxx::LoggerPtr firstLogger(log4cxx::Logger::getLogger("first.log"));
    log4cxx::LoggerPtr secondLogger(log4cxx::Logger::getLogger("second.log"));
public:
    virtual void writeLogMessage(log4cxx::LoggerPtd logger, std::string msg);
};

Is what I am doing by passing that LoggerPtr the right way of doing it? Because I need to be able to select which logger to use.

Also, if creating a logging interface is better, can someone suggest a good example where one can see the nitty gritty of how to implement such an interface using log4cxx? So, for example, what needs to be private and what needs to be public etc.

Upvotes: 0

Views: 413

Answers (1)

Nathan
Nathan

Reputation: 6531

Yes, you shouldn't re-implement logging in your classes. It's repeating yourself and muddies the responsibilities of each class. Deciding which of the log4cxx::LoggerPtr to use sounds like something a calling class shouldn't have to care about and sounds like a decision that should be made the decision inside the Logger class

Don't create instances in your classes, however. Have an abstract class for your logger and pass it in to the constructors of your classes. Don't tie your classes to one logger implementation, rather pick it higher up or in your IOC configuration code. (I've never used IOC in C++, but this one looks good. Incidentally, will having multiple implementations of your logger solve your multiple log4cxx::LoggerPtr problem?

I would actually argue choosing how to format something that has happened into a readable std::string msg is the job of the logger, not the class. I would send some abstract Event class to the logger instead. I've been trying to remember what this pattern is called (if it is even a pattern), here's an example of it in another language

Upvotes: 2

Related Questions