QLoggingCategory Class

The QLoggingCategory class represents a category, or 'area' in the logging infrastructure. More...

Header: #include <QLoggingCategory>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

Note: All functions in this class are thread-safe.

Public Types

Public Functions

QLoggingCategory(const char *category, QtMsgType enableForLevel = QtDebugMsg)
~QLoggingCategory()
const char *categoryName() const
bool isCriticalEnabled() const
bool isDebugEnabled() const
bool isEnabled(QtMsgType msgtype) const
bool isInfoEnabled() const
bool isWarningEnabled() const
void setEnabled(QtMsgType type, bool enable)
QLoggingCategory &operator()()
const QLoggingCategory &operator()() const

Static Public Members

QLoggingCategory *defaultCategory()
QLoggingCategory::CategoryFilter installFilter(QLoggingCategory::CategoryFilter filter)
void setFilterRules(const QString &rules)

Macros

(since 6.5) Q_DECLARE_EXPORTED_LOGGING_CATEGORY(name, EXPORT_MACRO)
Q_DECLARE_LOGGING_CATEGORY(name)
Q_LOGGING_CATEGORY(name, string)
Q_LOGGING_CATEGORY(name, string, msgType)
qCCritical(category)
qCCritical(category, const char *message, ...)
qCDebug(category)
qCDebug(category, const char *message, ...)
(since 6.5) qCFatal(category)
(since 6.5) qCFatal(category, const char *message, ...)
qCInfo(category)
qCInfo(category, const char *message, ...)
qCWarning(category)
qCWarning(category, const char *message, ...)

Detailed Description

QLoggingCategory represents a certain logging category - identified by a string - at runtime. A category can be configured to enable or disable logging of messages per message type. An exception are fatal messages, which are always enabled.

To check whether a message type is enabled or not, use one of these methods: isDebugEnabled(), isInfoEnabled(), isWarningEnabled(), and isCriticalEnabled().

All objects are meant to be configured by a common registry, as described in Configuring Categories. Different objects can also represent the same category. Therefore, it's not recommended to export objects across module boundaries, to manipulate the objects directly, or to inherit from QLoggingCategory.

Creating Category Objects

The Q_DECLARE_LOGGING_CATEGORY() and Q_LOGGING_CATEGORY() macros conveniently declare and create QLoggingCategory objects:

// in a header
Q_DECLARE_LOGGING_CATEGORY(driverUsb)

// in one source file
Q_LOGGING_CATEGORY(driverUsb, "driver.usb")

There is also the Q_DECLARE_EXPORTED_LOGGING_CATEGORY() macro in order to use a logging category across library boundaries.

Category names are free text; to configure categories using Logging Rules, their names should follow this convention:

  • Use letters and numbers only.
  • Use dots to further structure categories into common areas.
  • Avoid the category names: debug, info, warning, and critical.
  • Category names with the qt prefix are solely reserved for Qt modules.

QLoggingCategory objects that are implicitly defined by Q_LOGGING_CATEGORY() are created on first use, in a thread-safe manner.

Checking Category Configuration

QLoggingCategory provides isDebugEnabled(), isInfoEnabled(), isWarningEnabled(), isCriticalEnabled(), as well as isEnabled() to check whether messages for the given message type should be logged.

The qCDebug(), qCWarning(), and qCCritical() macros prevent arguments from being evaluated if the respective message types are not enabled for the category, so explicit checking is not needed:

    // usbEntries() will only be called if driverUsb category is enabled
    qCDebug(driverUsb) << "devices: " << usbEntries();

Default Category Configuration

Both the QLoggingCategory constructor and the Q_LOGGING_CATEGORY() macro accept an optional QtMsgType argument, which disables all message types with a lower severity. That is, a category declared with

Q_LOGGING_CATEGORY(driverUsbEvents, "driver.usb.events", QtWarningMsg)

logs messages of type QtWarningMsg, QtCriticalMsg, QtFatalMsg, but ignores messages of type QtDebugMsg and QtInfoMsg.

If no argument is passed, all messages are logged. Only Qt internal categories which start with qt are handled differently: For these, only messages of type QtInfoMsg, QtWarningMsg, QtCriticalMsg, and QFatalMsg are logged by default.

Note: Logging categories are not affected by your C++ build configuration. That is, whether messages are printed does not change depending on whether the code is compiled with debug symbols ('Debug Build'), optimizations ('Release Build'), or some other combination.

Configuring Categories

You can override the default configuration for categories either by setting logging rules, or by installing a custom filter.

Logging Rules

Logging rules let you enable or disable logging for categories in a flexible way. Rules are specified in text, where every line must have the format:

    <category>[.<type>] = true|false

<category> is the name of the category, potentially with * as a wildcard symbol for the first or last character; or at both positions. The optional <type> must be debug, info, warning, or critical. Lines that don't fit this scheme are ignored.

Rules are evaluated in text order, from first to last. That is, if two rules apply to a category/type, the rule that comes later is applied.

Rules can be set via setFilterRules():

    QLoggingCategory::setFilterRules("*.debug=false\n"
                                     "driver.usb.debug=true");

Logging rules are automatically loaded from the [Rules] section in a logging configuration file. These configuration files are looked up in the QtProject configuration directory, or explicitly set in a QT_LOGGING_CONF environment variable:

    [Rules]
    *.debug=false
    driver.usb.debug=true

Logging rules can also be specified in a QT_LOGGING_RULES environment variable; multiple rules can also be separated by semicolons:

    QT_LOGGING_RULES="*.debug=false;driver.usb.debug=true"

Rules set by setFilterRules() take precedence over rules specified in the QtProject configuration directory. In turn, these rules can be overwritten by those from the configuration file specified by QT_LOGGING_CONF, and those set by QT_LOGGING_RULES.

The order of evaluation is as follows:

  1. [QLibraryInfo::DataPath]/qtlogging.ini
  2. QtProject/qtlogging.ini
  3. setFilterRules()
  4. QT_LOGGING_CONF
  5. QT_LOGGING_RULES

The QtProject/qtlogging.ini file is looked up in all directories returned by QStandardPaths::GenericConfigLocation.

Set the QT_LOGGING_DEBUG environment variable to find out where your logging rules are loaded from.

Installing a Custom Filter

As a lower-level alternative to the text rules, you can also implement a custom filter via installFilter(). All filter rules are ignored in this case.

Printing the Category

Use the %{category} placeholder to print the category in the default message handler:

    qSetMessagePattern("%{category} %{message}");

Member Type Documentation

QLoggingCategory::CategoryFilter

This is a typedef for a pointer to a function with the following signature:

void myCategoryFilter(QLoggingCategory *);

A function with this signature can be installed with installFilter().

Member Function Documentation

[explicit] QLoggingCategory::QLoggingCategory(const char *category, QtMsgType enableForLevel = QtDebugMsg)

Constructs a QLoggingCategory object with the provided category name, and enables all messages with types at least as verbose as enableForLevel, which defaults to QtDebugMsg (which enables all categories).

If category is nullptr, the category name "default" is used.

Note: category must be kept valid during the lifetime of this object. Using a string literal for it is the usual way to achieve this.

[noexcept] QLoggingCategory::~QLoggingCategory()

Destroys a QLoggingCategory object.

const char *QLoggingCategory::categoryName() const

Returns the name of the category.

[static] QLoggingCategory *QLoggingCategory::defaultCategory()

Returns a pointer to the global category "default" that is used, for example, by qDebug(), qInfo(), qWarning(), qCritical(), or qFatal().

Note: The pointer returned may be null during destruction of static objects. Also, don't delete this pointer, as ownership of the category isn't transferred.

[static] QLoggingCategory::CategoryFilter QLoggingCategory::installFilter(QLoggingCategory::CategoryFilter filter)

Take control of how logging categories are configured.

Installs a function filter that is used to determine which categories and message types should be enabled. If filter is nullptr, the default message filter is reinstated. Returns a pointer to the previously-installed filter.

Every QLoggingCategory object that already exists is passed to the filter before installFilter() returns, and the filter is free to change each category's configuration with setEnabled(). Any category it doesn't change will retain the configuration it was given by the prior filter, so the new filter does not need to delegate to the prior filter during this initial pass over existing categories.

Any new categories added later will be passed to the new filter; a filter that only aims to tweak the configuration of a select few categories, rather than completely overriding the logging policy, can first pass the new category to the prior filter, to give it its standard configuration, and then tweak that as desired, if it is one of the categories of specific interest to the filter. The code that installs the new filter can record the return from installFilter() for the filter to use in such later calls.

When you define your filter, note that it can be called from different threads; but never concurrently. This filter cannot call any static functions from QLoggingCategory.

Example:

static QLoggingCategory::CategoryFilter oldCategoryFilter = nullptr;

void myCategoryFilter(QLoggingCategory *category)
{
    // For a category set up after this filter is installed, we first set it up
    // with the old filter. This ensures that any driver.usb logging configured
    // by the user is kept, aside from the one level we override; and any new
    // categories we're not interested in get configured by the old filter.
    if (oldCategoryFilter)
        oldCategoryFilter(category);

    // Tweak driver.usb's logging, over-riding the default filter:
    if (qstrcmp(category->categoryName(), "driver.usb") == 0)
        category->setEnabled(QtDebugMsg, true);
}

installed (in main(), for example) by

oldCategoryFilter = QLoggingCategory::installFilter(myCategoryFilter);

Alternatively, you can configure the default filter via setFilterRules().

bool QLoggingCategory::isCriticalEnabled() const

Returns true if critical messages should be shown for this category; false otherwise.

Note: The qCCritical() macro already does this check before executing any code. However, calling this method may be useful to avoid the expensive generation of data for debug output only.

bool QLoggingCategory::isDebugEnabled() const

Returns true if debug messages should be shown for this category; false otherwise.

Note: The qCDebug() macro already does this check before running any code. However, calling this method may be useful to avoid the expensive generation of data for debug output only.

bool QLoggingCategory::isEnabled(QtMsgType msgtype) const

Returns true if a message of type msgtype for the category should be shown; false otherwise.

bool QLoggingCategory::isInfoEnabled() const

Returns true if informational messages should be shown for this category; false otherwise.

Note: The qCInfo() macro already does this check before executing any code. However, calling this method may be useful to avoid the expensive generation of data for debug output only.

bool QLoggingCategory::isWarningEnabled() const

Returns true if warning messages should be shown for this category; false otherwise.

Note: The qCWarning() macro already does this check before executing any code. However, calling this method may be useful to avoid the expensive generation of data for debug output only.

void QLoggingCategory::setEnabled(QtMsgType type, bool enable)

Changes the message type type for the category to enable.

This method is meant for use only from inside a filter installed with installFilter(). For an overview on how to configure categories globally, see Configuring Categories.

Note: QtFatalMsg cannot be changed; it will always remain true.

See also isEnabled().

[static] void QLoggingCategory::setFilterRules(const QString &rules)

Configures which categories and message types should be enabled through a set of rules.

Example:

    QLoggingCategory::setFilterRules(QStringLiteral("driver.usb.debug=true"));

Note: The rules might be ignored if a custom category filter is installed with installFilter(), or if the user has defined the QT_LOGGING_CONF or the QT_LOGGING_RULES environment variable.

QLoggingCategory &QLoggingCategory::operator()()

Returns the object itself. This allows for both: a QLoggingCategory variable, and a factory method that returns a QLoggingCategory, to be used in qCDebug(), qCWarning(), qCCritical(), or qCFatal() macros.

const QLoggingCategory &QLoggingCategory::operator()() const

Returns the object itself. This allows for both: a QLoggingCategory variable, and a factory method that returns a QLoggingCategory, to be used in qCDebug(), qCWarning(), qCCritical(), or qCFatal() macros.

Macro Documentation

[since 6.5] Q_DECLARE_EXPORTED_LOGGING_CATEGORY(name, EXPORT_MACRO)

Declares a logging category name. The macro can be used to declare a common logging category shared in different parts of the program.

This works exactly like Q_DECLARE_LOGGING_CATEGORY(). However, the logging category declared by this macro is additionally qualified with EXPORT_MACRO. This is useful if the logging category needs to be exported from a dynamic library.

For example:

Q_DECLARE_EXPORTED_LOGGING_CATEGORY(lcCore, LIB_EXPORT_MACRO)

This macro must be used outside of a class or function.

This macro was introduced in Qt 6.5.

See also Q_LOGGING_CATEGORY() and Q_DECLARE_LOGGING_CATEGORY().

Q_DECLARE_LOGGING_CATEGORY(name)

Declares a logging category name. The macro can be used to declare a common logging category shared in different parts of the program.

This macro must be used outside of a class or method.

See also Q_LOGGING_CATEGORY() and Q_DECLARE_EXPORTED_LOGGING_CATEGORY().

Q_LOGGING_CATEGORY(name, string)

Defines a logging category name, and makes it configurable under the string identifier. By default, all message types are enabled.

Only one translation unit in a library or executable can define a category with a specific name. The implicitly-defined QLoggingCategory object is created on first use, in a thread-safe manner.

This macro must be used outside of a class or method.

See also Q_DECLARE_LOGGING_CATEGORY() and Q_DECLARE_EXPORTED_LOGGING_CATEGORY().

Q_LOGGING_CATEGORY(name, string, msgType)

Defines a logging category name, and makes it configurable under the string identifier. By default, messages of QtMsgType msgType and more severe are enabled, types with a lower severity are disabled.

Only one translation unit in a library or executable can define a category with a specific name. The implicitly-defined QLoggingCategory object is created on first use, in a thread-safe manner.

This macro must be used outside of a class or method.

See also Q_DECLARE_LOGGING_CATEGORY().

qCCritical(category)

Returns an output stream for critical messages in the logging category, category.

The macro expands to code that checks whether QLoggingCategory::isCriticalEnabled() evaluates to true. If so, the stream arguments are processed and sent to the message handler.

Example:

    QLoggingCategory category("driver.usb");
    qCCritical(category) << "a critical message";

Note: If the critical output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qCritical().

qCCritical(category, const char *message, ...)

Logs a critical message, message, in the logging category, category. message may contain place holders to be replaced by additional arguments, similar to the C printf() function.

Example:

    QLoggingCategory category("driver.usb");
    qCCritical(category, "a critical message logged into category %s", category.categoryName());

Note: If the critical output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qCritical().

qCDebug(category)

Returns an output stream for debug messages in the logging category, category.

The macro expands to code that checks whether QLoggingCategory::isDebugEnabled() evaluates to true. If so, the stream arguments are processed and sent to the message handler.

Example:

    QLoggingCategory category("driver.usb");
    qCDebug(category) << "a debug message";

Note: Arguments aren't processed if the debug output for that category is not enabled, so don't rely on any side effects.

See also qDebug().

qCDebug(category, const char *message, ...)

Logs a debug message, message, in the logging category, category. message may contain place holders to be replaced by additional arguments, similar to the C printf() function.

Example:

    QLoggingCategory category("driver.usb");
    qCDebug(category, "a debug message logged into category %s", category.categoryName());

Note: Arguments aren't processed if the debug output for that category is not enabled, so don't rely on any side effects.

See also qDebug().

[since 6.5] qCFatal(category)

Returns an output stream for fatal messages in the logging category, category.

If you are using the default message handler, the returned stream will abort to create a core dump. On Windows, for debug builds, this function will report a _CRT_ERROR enabling you to connect a debugger to the application.

Example:

    QLoggingCategory category("driver.usb");
    qCFatal(category) << "a fatal message. Program will be terminated!";

This macro was introduced in Qt 6.5.

See also qFatal().

[since 6.5] qCFatal(category, const char *message, ...)

Logs a fatal message, message, in the logging category, category. message may contain place holders to be replaced by additional arguments, similar to the C printf() function.

Example:

    QLoggingCategory category("driver.usb");
    qCFatal(category, "a fatal message. Program will be terminated!");

If you are using the default message handler, this function will abort to create a core dump. On Windows, for debug builds, this function will report a _CRT_ERROR enabling you to connect a debugger to the application.

This macro was introduced in Qt 6.5.

See also qFatal().

qCInfo(category)

Returns an output stream for informational messages in the logging category, category.

The macro expands to code that checks whether QLoggingCategory::isInfoEnabled() evaluates to true. If so, the stream arguments are processed and sent to the message handler.

Example:

    QLoggingCategory category("driver.usb");
    qCInfo(category) << "an informational message";

Note: If the debug output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qInfo().

qCInfo(category, const char *message, ...)

Logs an informational message, message, in the logging category, category. message may contain place holders to be replaced by additional arguments, similar to the C printf() function.

Example:

    QLoggingCategory category("driver.usb");
    qCInfo(category, "an informational message logged into category %s", category.categoryName());

Note: If the debug output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qInfo().

qCWarning(category)

Returns an output stream for warning messages in the logging category, category.

The macro expands to code that checks whether QLoggingCategory::isWarningEnabled() evaluates to true. If so, the stream arguments are processed and sent to the message handler.

Example:

    QLoggingCategory category("driver.usb");
    qCWarning(category) << "a warning message";

Note: If the warning output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qWarning().

qCWarning(category, const char *message, ...)

Logs a warning message, message, in the logging category, category. message may contain place holders to be replaced by additional arguments, similar to the C printf() function.

Example:

    QLoggingCategory category("driver.usb");
    qCWarning(category, "a warning message logged into category %s", category.categoryName());

Note: If the warning output for a particular category isn't enabled, arguments won't be processed, so don't rely on any side effects.

See also qWarning().

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.