Colored logging in Qt & QtCreator

I’ve just come across this article at woboq about improving debug output in Qt. It turns out there’s a config variable named QT_MESSAGE_PATTERN which holds the format of the debug messages (printed by qDebug and qInfo among others).

You can use several different placeholders, like %{threadid} to output the current thread ID and so on. You can see all the available placeholders here in the docs. ANSI color codes can be used as well.

You can set it as an environment variable, from within your code, using setenv, or use qSetMessagePattern, like so:

        "\033[32m%{time h:mm:ss}"
        "\033[33m %{threadid} "
        "%{if-category}\033[32m %{category}:%{endif}"
        "%{if-warning}\033[31m%{backtrace depth=3}%{endif}"
        "%{if-critical}\033[31m%{backtrace depth=3}%{endif}"
        "%{if-fatal}\033[31m%{backtrace depth=3}%{endif}"
        "\033[0m %{message}"

 And the debug output will look like this (in QtCreator and also in the terminal):

2018-02-07 14_20_03-f110d2_3 (jttocinog)

Ain’t that cool or what.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.