Łukasz Przeniosło Łukasz Przeniosło - 1 month ago 27
C++ Question

How does QMessageLogger magic work?

I am working on a logger framework for QT applications. I am not using

QMessageLogger
directly because of understanding and learning purposes. There is one thing about one
QMessageLogger
functionality that I would really like to have in my logger but I dont know how does it work. Lets take for example the
qDebug
macro:

#define qDebug QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC).debug


One can call this function in 2 ways:
1st way:

qDebug("abc = %u", abc);


2nd way:

qDebug() << "abc = " << abc;


I am looking at the library code, but I cannot quite understand how is it implemented that one can work with
QMessageLogger
by using
va_args
as well as some stream object.
How can I achieve such effect? I would really appreciate all help, would be grateful for an example.

Here is my
print
method body. I need to achieve simmilar functionality with the "stream" way:

/*!
* \brief Adds the log line to the print queue.
* \param lvl: Log level of the line.
* \param text: Formatted input for va_list.
*/
void CBcLogger::print(MLL::ELogLevel lvl, const char* text, ...)
{
// check if logger initialized
if (!m_loggerStarted)
return;

// check if log level sufficient
if (lvl > m_setLogLvl)
return;

logLine_t logline;
logline.loglvl = lvl;
logline.datetime = QDateTime::currentDateTime();

va_list argptr;
va_start(argptr, text);

char* output = NULL;
if (vasprintf(&output, text, argptr))
{
logline.logstr = output;
delete output;
}

va_end(argptr);
emit addNewLogLine(logline);
}

Answer

First, you need to understand what is the following

QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC).debug

The above line constructs a QMessageLogger instance and immediately accesses its debug member. Since it is a macro, it's also important what you write in code right after it.

If you look at what QMessageLogger::debug is, you'll see four overloads, and the first two of them are pertinent to your question:

void debug(const char *msg, ...) const Q_ATTRIBUTE_FORMAT_PRINTF(2, 3);
QDebug debug() const;
QDebug debug(const QLoggingCategory &cat) const;
QDebug debug(CategoryFunction catFunc) const;

Now the matter should be simple. If you call qDebug("abc = %u", abc), you're calling the first overload, and the expanded macro is as follows:

QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC).debug("abc = %u", abc)

which is more or less equal to

QMessageLogger temp(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC);
temp.debug("abc = %u", abc);

In the second case you're calling an overload that returns a QDebug object. QDebug has overloaded operator<<. The expanded macro is as follows:

QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC).debug() << "abc = " << abc;

which is more or less equal to

QMessageLogger temp(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC);
QDebug anotherTemp = temp.debug();
anotherTemp << "abc = " << abc;

Here's a simple implementation of such logger:

void addNewLogLine(char const* ptr){
    cout << "addNewLogLine: " << ptr << endl;
}
struct LoggerHelper
{
    std::stringstream s;

    explicit LoggerHelper()=default;
    LoggerHelper(LoggerHelper&&) = default;

    ~LoggerHelper(){
        auto str = s.str();
        addNewLogLine(str.c_str());
    }

    template<typename T>
    LoggerHelper& operator<<(T const& val){
        s << val;
        return *this;
    }
};

struct Logger
{
    void operator()(char const* fmt, ...) const {
        char* buf;
        va_list args;
        va_start(args, fmt);
        vasprintf(&buf, fmt, args);
        va_end(args);
        addNewLogLine(buf);
        free(buf);
    }

    LoggerHelper operator()() const {
        return LoggerHelper{};
    }
};

demo

Several notes:

  • I adhered to your interface, but personally, I'd use variadic templates instead of va_args
  • you're supposed to free the buffer returned by vasprintf. free is not interchangeable with delete or delete[]
  • I used std::stringstream, but changing it to QTextStream or any other should be simple enough
  • You don't need to implement helper as a separate class if you're okay with allowing log << "foo" << "bar" syntax as opposed to log() << "foo" << "bar"