<QtLogging> - Qt Logging Types

The <QtLogging> header file defines Qt logging types, functions and macros. 更多...

头: #include <QtLogging>

类型

QtMessageHandler
enum QtMsgType { QtDebugMsg, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtSystemMsg }

函数

QString qFormatLogMessage (QtMsgType type , const QMessageLogContext & context , const QString & str )
QtMessageHandler qInstallMessageHandler (QtMessageHandler handler )
void qSetMessagePattern (const QString & pattern )

qCritical (const char * message , ...)
qDebug (const char * message , ...)
qFatal (const char * message , ...)
qInfo (const char * message , ...)
qWarning (const char * message , ...)

详细描述

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 类。

<QtLogging> also contains functions that generate messages from the given string argument: qDebug (), qInfo (), qWarning (), qCritical (),和 qFatal (). These functions call the message handler with the given message.

范例:

if (!driver()->isOpen() || driver()->isOpenError()) {
    qWarning("QSqlQuery::exec: database not open");
    return false;
}
					

类型文档编制

QtMessageHandler

这是采用以下签名的函数指针的 typedef:

void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);
					

另请参阅 QtMsgType and qInstallMessageHandler ().

enum QtMsgType

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.

常量 描述
QtDebugMsg 0 消息的生成通过 qDebug () 函数。
QtInfoMsg 4 消息的生成通过 qInfo () 函数。
QtWarningMsg 1 消息的生成通过 qWarning () 函数。
QtCriticalMsg 2 消息的生成通过 qCritical () 函数。
QtFatalMsg 3 消息的生成通过 qFatal () 函数。
QtSystemMsg QtCriticalMsg

QtInfoMsg 在 Qt 5.5 添加。

另请参阅 QtMessageHandler and qInstallMessageHandler ().

函数文档编制

QString qFormatLogMessage ( QtMsgType type , const QMessageLogContext & context , const QString & str )

Generates a formatted string out of the type , context , str 自变量。

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.

另请参阅 qInstallMessageHandler () 和 qSetMessagePattern ().

QtMessageHandler qInstallMessageHandler ( QtMessageHandler handler )

Installs a Qt message handler which has been defined previously. Returns a pointer to the previous message handler.

The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur. Qt built in release mode also contains such warnings unless QT_NO_WARNING_OUTPUT and/or QT_NO_DEBUG_OUTPUT have been set during compilation. If you implement your own message handler, you get total control of these messages.

The default message handler prints the message to the standard output under X11 or to the debugger under Windows. If it is a fatal message, the application aborts immediately after handling that message. Custom message handlers should not attempt to exit an application on their own.

Only one message handler can be defined, since this is usually done on an application-wide basis to control debug output.

To restore the message handler, call qInstallMessageHandler(0) .

范例:

#include <qapplication.h>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    const char *file = context.file ? context.file : "";
    const char *function = context.function ? context.function : "";
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    }
}
int main(int argc, char **argv)
{
    qInstallMessageHandler(myMessageOutput);
    QApplication app(argc, argv);
    ...
    return app.exec();
}
					

另请参阅 QtMessageHandler , QtMsgType , qDebug (), qInfo (), qWarning (), qCritical (), qFatal (),和 调试技术 .

void qSetMessagePattern (const QString & pattern )

Changes the output of the default message handler.

Allows to tweak the output of qDebug (), qInfo (), qWarning (), qCritical (),和 qFatal (). The category logging output of qCDebug (), qCInfo (), qCWarning (),和 qCCritical () is formatted, too.

Following placeholders are supported:

Placeholder 描述
%{appname} QCoreApplication::applicationName ()
%{category} Logging category
%{file} Path to source file
%{function} 函数
%{line} Line in source file
%{message} The actual message
%{pid} QCoreApplication::applicationPid ()
%{threadid} The system-wide ID of current thread (if it can be obtained)
%{qthreadptr} A pointer to the current QThread (result of QThread::currentThread ())
%{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 QElapsedTimer::msecsSinceReference ()).
%{time [format]} system time when the message occurred, formatted by passing the format to QDateTime::toString (). If the format is not specified, the format of Qt::ISODate 被使用。
%{backtrace [depth=N] [separator="..."]} A backtrace with the number of frames specified by the optional depth parameter (defaults to 5), and separated by the optional separator parameter (defaults to "|").

This expansion is available only on some platforms (currently only platfoms using glibc). 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.

范例:

    QT_MESSAGE_PATTERN="[%{time yyyyMMdd h:mm:ss.zzz t} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}"
				

默认 pattern is %{if-category}%{category}: %{endif}%{message} .

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.

注意: 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 文档编制。

注意: 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.

另请参阅 qInstallMessageHandler (), 调试技术 , QLoggingCategory ,和 QMessageLogContext .

宏文档编制

qCritical (const char * message , ...)

Calls the message handler with the critical message message . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2.

It exits if the environment variable QT_FATAL_CRITICALS is not empty.

This function takes a format string and a list of arguments, similar to the C printf() function. The format should be a Latin-1 string.

范例:

void load(const QString &fileName)
{
    QFile file(fileName);
    if (!file.exists())
        qCritical("File '%s' does not exist!", qUtf8Printable(fileName));
}
				

If you include <QtDebug>, a more convenient syntax is also available:

qCritical() << "Brush:" << myQBrush << "Other value:" << i;
				

A space is inserted between the items, and a newline is appended at the end.

To suppress the output at runtime, install your own message handler with qInstallMessageHandler ().

注意: This macro is thread-safe .

另请参阅 qDebug (), qInfo (), qWarning (), qFatal (), qInstallMessageHandler (),和 调试技术 .

qDebug (const char * message , ...)

Calls the message handler with the debug message message . If no message handler has been installed, the message is printed to stderr. Under Windows the message is sent to the console, if it is a console application; otherwise, it is sent to the debugger. On QNX, the message is sent to slogger2. This function does nothing if QT_NO_DEBUG_OUTPUT was defined during compilation.

If you pass the function a format string and a list of arguments, it works in similar way to the C printf() function. The format should be a Latin-1 string.

范例:

qDebug("Items in list: %d", myList.size());
				

If you include <QtDebug> , a more convenient syntax is also available:

qDebug() << "Brush:" << myQBrush << "Other value:" << i;
				

采用此句法,函数返回 QDebug object that is configured to use the QtDebugMsg message type. It automatically puts a single space between each item, and outputs a newline at the end. It supports many C++ and Qt types.

To suppress the output at runtime, install your own message handler with qInstallMessageHandler ().

注意: This macro is thread-safe .

另请参阅 qInfo (), qWarning (), qCritical (), qFatal (), qInstallMessageHandler (),和 调试技术 .

qFatal (const char * message , ...)

Calls the message handler with the fatal message message . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2.

若正使用 默认消息处理程序 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 function takes a format string and a list of arguments, similar to the C printf() function.

范例:

int divide(int a, int b)
{
    if (b == 0)                                // program error
        qFatal("divide: cannot divide by zero");
    return a / b;
}
				

To suppress the output at runtime, install your own message handler with qInstallMessageHandler ().

另请参阅 qDebug (), qInfo (), qWarning (), qCritical (), qInstallMessageHandler (),和 调试技术 .

qInfo (const char * message , ...)

Calls the message handler with the informational message message . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the console, if it is a console application; otherwise, it is sent to the debugger. On QNX the message is sent to slogger2. This function does nothing if QT_NO_INFO_OUTPUT was defined during compilation.

If you pass the function a format string and a list of arguments, it works in similar way to the C printf() function. The format should be a Latin-1 string.

范例:

qInfo("Items in list: %d", myList.size());
				

If you include <QtDebug> , a more convenient syntax is also available:

qInfo() << "Brush:" << myQBrush << "Other value:" << i;
				

采用此句法,函数返回 QDebug object that is configured to use the QtInfoMsg message type. It automatically puts a single space between each item, and outputs a newline at the end. It supports many C++ and Qt types.

To suppress the output at runtime, install your own message handler using qInstallMessageHandler ().

注意: This macro is thread-safe .

另请参阅 qDebug (), qWarning (), qCritical (), qFatal (), qInstallMessageHandler (),和 调试技术 .

qWarning (const char * message , ...)

调用消息处理程序采用警告消息 message . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2. This function does nothing if QT_NO_WARNING_OUTPUT was defined during compilation; it exits if at the nth warning corresponding to the counter in environment variable QT_FATAL_WARNINGS . That is, if the environment variable contains the value 1, it will exit on the 1st message; if it contains the value 10, it will exit on the 10th message. Any non-numeric value is equivalent to 1.

This function takes a format string and a list of arguments, similar to the C printf() function. The format should be a Latin-1 string.

范例:

void f(int c)
{
    if (c > 200)
        qWarning("f: bad argument, c == %d", c);
}
				

If you include <QtDebug>, a more convenient syntax is also available:

qWarning() << "Brush:" << myQBrush << "Other value:" << i;
				

This syntax inserts a space between each item, and appends a newline at the end.

To suppress the output at runtime, install your own message handler with qInstallMessageHandler ().

注意: This macro is thread-safe .

另请参阅 qDebug (), qInfo (), qCritical (), qFatal (), qInstallMessageHandler (),和 调试技术 .