Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
The <QtLogging> header file defines Qt logging types, functions and macros.
The <QtLogging> header file contains several types, functions and macros for logging.
The QtMsgType enum identifies the various messages that can be generated and sent to a Qt message handler; QtMessageHandler is a type definition for a pointer to a function with the signature void myMessageHandler(QtMsgType, const QMessageLogContext &, const char *). qInstallMessageHandler() function can be used to install the given QtMessageHandler . QMessageLogContext class contains the line, file, and function the message was logged at. This information is created by the QMessageLogger class.
<QtLogging> also contains functions that generate messages from the given string argument: qDebug() , qInfo() , qWarning() , qCritical() , and qFatal() . These functions call the message handler with the given message.
Example:
if not driver().isOpen() or driver().isOpenError(): qWarning("QSqlQuery.exec: database not open") return FalseSee also
Logs critical message format to the central message handler. format can contain format specifiers that are replaced by values specificed in additional arguments.
Example:
def load(fileName): file = QFile(fileName) if not file.exists(): qCritical("File '%s' does not exist!", qUtf8Printable(fileName))
format can contain format specifiers like %s for UTF-8 strings, or %i for integers. This is similar to how the C printf() function works. For more details on the formatting, see asprintf() .
For more convenience and further type support, you can also use qCritical() , which follows the streaming paradigm (similar to std::cout or std::cerr).
To suppress the output at runtime, you can define logging rules or register a custom filter .
For debugging purposes, it is sometimes convenient to let the program abort for critical messages. This allows you to inspect the core dump, or attach a debugger - see also qFatal() . To enable this, set the environment variable QT_FATAL_CRITICALS to a number n. The program terminates then for the n-th critical message. That is, if the environment variable is set to 1, it will terminate on the first call; if it contains the value 10, it will exit on the 10th call. Any non-numeric value in the environment variable is equivalent to 1.
See also
qCriticalqCCritical()qDebug()qInfo()qWarning()qFatal()qInstallMessageHandler()Debugging Techniques
Logs debug message format to the central message handler. format can contain format specifiers that are replaced by values specificed in additional arguments.
Example:
qDebug("Items in list: %d", myList.size())
format can contain format specifiers like %s for UTF-8 strings, or %i for integers. This is similar to how the C printf() function works. For more details on the formatting, see asprintf() .
For more convenience and further type support, you can also use qDebug() , which follows the streaming paradigm (similar to std::cout or std::cerr).
This function does nothing if QT_NO_DEBUG_OUTPUT was defined during compilation.
To suppress the output at runtime, install your own message handler with qInstallMessageHandler() .
See also
qDebug()qCDebug()qInfo()qWarning()qCritical()qFatal()qInstallMessageHandler()Debugging Techniques
Logs fatal message format to the central message handler. format can contain format specifiers that are replaced by values specificed in additional arguments.
Example:
def divide(a,b): if b == 0: # program error qFatal("divide: cannot divide by zero") return a / b
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.
To suppress the output at runtime, install your own message handler with qInstallMessageHandler() .
See also
qCFatal()qDebug()qInfo()qWarning()qCritical()qInstallMessageHandler()Debugging Techniques
Generates a formatted string out of the type, context, str arguments.
qFormatLogMessage returns a QString that is formatted according to the current message pattern. It can be used by custom message handlers to format output similar to Qt’s default message handler.
The function is thread-safe.
See also
qInstallMessageHandler()qSetMessagePattern()
Logs informational message format to the central message handler. format can contain format specifiers that are replaced by values specificed in additional arguments.
Example:
qInfo("Items in list: %d", myList.size())
format can contain format specifiers like %s for UTF-8 strings, or %i for integers. This is similar to how the C printf() function works. For more details on the formatting, see asprintf() .
For more convenience and further type support, you can also use qInfo() , which follows the streaming paradigm (similar to std::cout or std::cerr).
This function does nothing if QT_NO_INFO_OUTPUT was defined during compilation.
To suppress the output at runtime, install your own message handler using qInstallMessageHandler() .
See also
qInfo()qCInfo()qDebug()qWarning()qCritical()qFatal()qInstallMessageHandler()Debugging Techniques
Installs a Qt message handler. Returns a pointer to the previously installed message handler.
A message handler is a function that prints out debug, info, warning, critical, and fatal messages from Qt’s logging infrastructure. By default, Qt uses a standard message handler that formats and prints messages to different sinks specific to the operating system and Qt configuration. Installing your own message handler allows you to assume full control, and for instance log messages to the file system.
Note that Qt supports logging categories for grouping related messages in semantic categories. You can use these to enable or disable logging per category and message type . As the filtering for logging categories is done even before a message is created, messages for disabled types and categories will not reach the message handler.
A message handler needs to be reentrant . That is, it might be called from different threads, in parallel. Therefore, writes to common sinks (like a database, or a file) often need to be synchronized.
Qt allows to enrich logging messages with further meta-information by calling qSetMessagePattern() , or setting the QT_MESSAGE_PATTERN environment variable. To keep this formatting, a custom message handler can use qFormatLogMessage() .
Try to keep the code in the message handler itself minimal, as expensive operations might block the application. Also, to avoid recursion, any logging messages generated in the message handler itself will be ignored.
The message handler should always return. For fatal messages , the application aborts immediately after handling that message.
Only one message handler can be installed at a time, for the whole application. If there was a previous custom message handler installed, the function will return a pointer to it. This handler can then be later reinstalled by another call to the method. Also, calling qInstallMessageHandler(nullptr) will restore the default message handler.
Here is an example of a message handler that logs to a local file before calling the default handler:
from PySide6.QtWidgets import QApplication originalHandler = None def logToFile(type, context, msg): message = qFormatLogMessage(type, context, msg) f = fopen("log.txt", "a") fprintf(f, "%s\n", qPrintable(message)) fflush(f) if originalHandler: originalHandler(type, context, msg) if __name__ == "__main__": originalHandler = qInstallMessageHandler(logToFile) app = QApplication([]) ... sys.exit(app.exec())
Note that the C++ standard guarantees that static FILE *f is initialized in a thread-safe way. We can also expect fprintf() and fflush() to be thread-safe, so no further synchronization is necessary.
See also
QtMessageHandlerQtMsgTypeqDebug()qInfo()qWarning()qCritical()qFatal()qFormatLogMessage()
Changes the output of the default message handler.
Allows to tweak the output of qDebug() , qInfo() , qWarning() , qCritical() , and qFatal() . The category logging output of qCDebug() , qCInfo() , qCWarning() , and qCCritical() is formatted, too.
Following placeholders are supported:
Placeholder
Description
%{appname}
%{category}Logging category
%{file}Path to source file
%{function}Function
%{line}Line in source file
%{message}The actual message
%{pid}
%{threadid}The system-wide ID of current thread (if it can be obtained)
%{threadname}The current thread name (if it can be obtained, or the thread ID, since Qt 6.10)
%{qthreadptr}A pointer to the current
QThread(result ofcurrentThread())
%{type}“debug”, “warning”, “critical” or “fatal”
%{time process}time of the message, in seconds since the process started (the token “process” is literal)
%{time boot}the time of the message, in seconds since the system boot if that can be determined (the token “boot” is literal). If the time since boot could not be obtained, the output is indeterminate (see
msecsSinceReference()).
%{time [format]}system time when the message occurred, formatted by passing the
formattotoString(). If the format is not specified, the format ofISODateis used.
%{backtrace [depth=N] [separator="..."]}A backtrace with the number of frames specified by the optional
depthparameter (defaults to 5), and separated by the optionalseparatorparameter (defaults to “|”).This expansion is available only on some platforms:
platforms using glibc;
platforms shipping C++23’s
<stacktrace>header (requires compiling Qt in C++23 mode).Depending on the platform, there are some restrictions on the function names printed by this expansion.
On some platforms, names are only known for exported functions. If you want to see the name of every function in your application, make sure your application is compiled and linked with
-rdynamic, or an equivalent of it.When reading backtraces, take into account that frames might be missing due to inlining or tail call optimization.
You can also use conditionals on the type of the message using %{if-debug}, %{if-info} %{if-warning}, %{if-critical} or %{if-fatal} followed by an %{endif}. What is inside the %{if-*} and %{endif} will only be printed if the type matches.
Finally, text inside %{if-category} … %{endif} is only printed if the category is not the default one.
Example:
QT_MESSAGE_PATTERN="[%{time yyyyMMdd h:mm:ss.zzz ttt} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}"
The default pattern is %{if-category}%{category}: %{endif}%{message}.
Note
On Android, the default pattern is %{message} because the category is used as tag since Android logcat has a dedicated field for the logging categories, see Android Logging . If a custom pattern including the category is used, applicationName() is used as tag .
The pattern can also be changed at runtime by setting the QT_MESSAGE_PATTERN environment variable; if both qSetMessagePattern() is called and QT_MESSAGE_PATTERN is set, the environment variable takes precedence.
Note
The information for the placeholders category, file, function and line is only recorded in debug builds. Alternatively, QT_MESSAGELOGCONTEXT can be defined explicitly. For more information refer to the QMessageLogContext documentation.
Note
The message pattern only applies to unstructured logging, such as the default stderr output. Structured logging such as systemd will record the message as is, along with as much structured information as can be captured.
Custom message handlers can use qFormatLogMessage() to take pattern into account.
See also
qInstallMessageHandler()QLoggingCategoryQMessageLogContext
Logs warning message format to the central message handler. format can contain format specifiers that are replaced by values specificed in additional arguments.
Example:
def f(c): if c > 200: qWarning("f: bad argument, c == %d", c)
format can contain format specifiers like %s for UTF-8 strings, or %i for integers. This is similar to how the C printf() function works. For more details on the formatting, see asprintf() .
For more convenience and further type support, you can also use qWarning() , which follows the streaming paradigm (similar to std::cout or std::cerr).
This function does nothing if QT_NO_WARNING_OUTPUT was defined during compilation. To suppress the output at runtime, you can set logging rules or register a custom filter .
For debugging purposes, it is sometimes convenient to let the program abort for warning messages. This allows you to inspect the core dump, or attach a debugger - see also qFatal() . To enable this, set the environment variable QT_FATAL_WARNINGS to a number n. The program terminates then for the n-th warning. That is, if the environment variable is set to 1, it will terminate on the first call; if it contains the value 10, it will exit on the 10th call. Any non-numeric value in the environment variable is equivalent to 1.
See also
qWarning()qCWarning()qDebug()qInfo()qCritical()qFatal()qInstallMessageHandler()Debugging Techniques
This enum describes the messages that can be sent to a message handler ( QtMessageHandler ). You can use the enum to identify and associate the various message types with the appropriate actions. Its values are, in order of increasing severity:
Constant
Description
QtDebugMsg
A message generated by the
qDebug()function.QtInfoMsg
A message generated by the
qInfo()function.QtWarningMsg
A message generated by the
qWarning()function.QtCriticalMsg
A message generated by the
qCritical()function.QtFatalMsg
A message generated by the
qFatal()function.See also
QtMessageHandlerqInstallMessageHandler()QLoggingCategory
This is a typedef for a pointer to a function with the following signature:
def myMessageHandler(QtMsgType, ,):See also
QtMsgTypeqInstallMessageHandler()