Posts Tagged With ‘logging&8217


QWidgetLogger: A Qt logging device for SLogLib

SLogLib is a flexible logging library written in C++. It comes with three logging devices: console, file, and memory but often there is a need to show log directly on the user interface. I heavily use Qt for all projects requiring user interface, so I wrote a logging device for QWidget. It is available in SLogLib repository in the Contrib/QWidgetLogger folder.

Here is how to use the QWidgetLogger:

QWidgetLogger* logger = new QWidgetLogger(new HtmlFormatter(), "WidgetLogger");
SLogLib::addLoggingDevice(logger);

Once above code is added, any of the SLOGLIB_LOG_MSG_* logging macros will write to the QWidgetLogger as well as any other loggers added to SLogLib. QWidgetLogger internally uses SLogTextEdit class derived from QTextEdit. Instance of SLogTextEdit used by QWidgetLogger can be retrieved by QWidgetLogger::widget() function. This instance should be added to the UI to show the logging messages. QDockWidget is a good choice to show logging widget with QMainWindow.

SLogTextEdit sets a monospace 10 point font and it can be changed using style sheet. The color and style of the messages logged can also be changed using the Formatter. The HtmlFormatter used in the example above define different colors for different types of logging messages using HTML codes.

In Qt, UI elements can only be updated from the main thread but the logging messages might come from any thread. So SLogTextEdit checks if the message was posted from the main thread or some other worker thread. If the message was posted from a worker thread, SLogTextEdit emits a signal to only of its own private slot and updates itself in the slot. In Qt slots always run in the context of the main thread. This method works well but signal and slot mechanism is slow and update to widget lags while logging too many messages in a short period of time.