Lidbey
Lidbey

Reputation: 371

C++ QT Logger object

I am trying to create a globally accessible object (but I am not sure if creating a global object is a good solution) which will log to file my output stream. I would like it to work similar to std::cout, but with the difference that it would log to file.

class Logger
{
    QFile* file;
    QTextStream* stream;

public:
    Logger(QString filePath);
    {
        file = new QFile(filePath);
        if(file.open(QIODevice::ReadWrite)
            stream = new QTextStream(file);
    }
    QTextStream* Log()
    {
        return stream;
    }
};


int main(int argc, char *argv[])
{
    QString filePath="Logs.txt";
    Logger l(filePath);
    MyProgram a(argc, argv);
    return a.exec();
}

In case it would be global, all I would have to do is l.Log()<<"text I want to log in". I would prefer it to work like Log() << "text I want to log in", but any solution would be useful! :)

I want to also mention that I have came into a logger solution on web already, but it includes creating a temporary object - in my case constantly opening and closing file each time I want to log some text is not a solution. (unless this object would use some globally open file)

Upvotes: 0

Views: 682

Answers (1)

Ghasem Ramezani
Ghasem Ramezani

Reputation: 2888

What you need is Singleton Design Pattern. In the entire program, you need only one object of your logger class. So you need to use Singleton Design Pattern and place it into a separate file and just included it in whatever you need the logger.


For using streaming like operators (shift operator <<), you simply need to overload it:

friend Logger& operator<<(Logger& other, QString const& message)
{
        (*other.stream) << message;
        return other;
}

But in the case of Logger, it's not that simple you written. A logger base requirement are:

  1. Efficiently, to be fast enough in high rate logging.
  2. Thread safe, to could be used in multi-threaded programs.
  3. Formatting, to be used easily.
  4. Log leveling, to could categorize logs.

Take a look at: qDebug(), qInfo(), qWarning() and qFatal(). My suggestion for logging libraries are:

  1. Boost.Log
  2. Speed Log

Upvotes: 1

Related Questions