Qt qInstallMessageHandler(自定义消息处理)

前言

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.

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).

这是官方说明,主要的意思就是:

安装自定义的消息处理程序,返回指向上一个消息处理程序的指针。

消息处理程序是一个支持打印调试信息、警告、关键和致命错误信息的函数。Qt库(debug模式)包含数以百计的警告信息,当内部错误(通常是无效的函数参数)发生时,会打印出来。在Release模式下构建也包含这些警告,除非在编译时设置QT_NO_WARNING_OUTPUT和/或QT_NO_DEBUG_OUTPUT。如果你实现了自己的消息处理程序,你就可以完全控制这些消息。

默认消息处理程序将消息打印到 X11 下的标准输出或 Windows 下的调试器。如果是致命消息,应用程序会立即中止。

只能定义一个消息处理程序,因为这通常是在应用程序范围内完成的,以控制调试输出。

调用qInstallMessageHandler(0)可以恢复消息处理程序。

调试宏

Qt调试信息相关的宏有以下5种:

  • qDebug() :调试消息
  • qInfo():信息消息
  • qWarning():警告消息
  • qCritical() :错误消息
  • qFatal():致命错误消息

使用

在使用默认消息处理程序时,我们看一下调试输出的内容:

cpp 复制代码
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 打印信息
    qDebug() << "This is a debug message";
    qDebug("This is a debug message");
    qInfo("This is a info message");
    qWarning("This is a warning message");
    qCritical("This is a critical message");
    qFatal("This is a fatal message");
    
    return a.exec();
}

输出:

This is a debug message

This is a debug message

This is a info message

This is a warning message

This is a critical message

This is a fatal message

自定义消息处理程序

我们直接拿官网的示例来测试:

cpp 复制代码
#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[])
{
    QCoreApplication a(argc, argv);
    // 安装消息处理程序
    auto front = qInstallMessageHandler(myMessageOutput);
    // 打印信息
    qDebug() << "This is a debug message";
    qDebug("This is a debug message");
    qInfo("This is a info message");
    qWarning("This is a warning message");
    qCritical("This is a critical message");
    qFatal("This is a fatal message");
    
    return a.exec();
}

输出:

Debug: This is a debug message (...\main.cpp:88, int __cdecl main(int,char *[]))

Debug: This is a debug message (...\main.cpp:89, int __cdecl main(int,char *[]))

Info: This is a info message (...\main.cpp:90, int __cdecl main(int,char *[]))

Warning: This is a warning message (...\main.cpp:91, int __cdecl main(int,char *[]))

Critical: This is a critical message (...\main.cpp:92, int __cdecl main(int,char *[]))

Fatal: This is a fatal message (...\main.cpp:93, int __cdecl main(int,char *[]))

从上面示例看出我们可以去规范输出的格式,那么我们能不能决定输出的地方呢?比如直接输出到文件中?

自定义输出到文件

直接上代码:

cpp 复制代码
void myMessageOutputToFile(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
    QByteArray msgAry = msg.toLocal8Bit();

    QString msgTypeStr;
    switch (type) {
    case QtDebugMsg:
        msgTypeStr = QString("Debug");
        break;
    case QtInfoMsg:
        msgTypeStr = QString("Info");
        break;
    case QtWarningMsg:
        msgTypeStr = QString("Warning");
        break;
    case QtCriticalMsg:
        msgTypeStr = QString("Critical");
        break;
    case QtFatalMsg:
        msgTypeStr = QString("Fatal");
        break;
    }
    
    // 输出字符串格式化
    QString dateTimeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString msgStr = QString("[%1][%2] [%3:%4:%5]:%6").arg(dateTimeStr).arg(msgTypeStr)
                             .arg(context.file).arg(context.line).arg(context.function).arg(msgAry.constData());
    
    // 读写文件
    QFile file("log.txt");
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << msgStr << "\r\n";
    file.flush();
    file.close();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // 安装消息处理程序
    auto front = qInstallMessageHandler(myMessageOutputToFile);
    
    // 打印信息
    qDebug() << "This is a debug message";
    qDebug("This is a debug message");
    qInfo("This is a info message");
    qWarning("This is a warning message");
    qCritical("This is a critical message");
    qFatal("This is a fatal message");
    
    return a.exec();
}

输出:

注意:

上面输出到文件的方法是有问题的,这里只是进行简单的测试,问题主要有:

  1. 文件每次调用都要openclose
  2. 线程不安全
  3. 没有日志缓冲,直接写文件,性能会有问题

感兴趣的可以在这个基础上,实现一个线程安全的缓冲日志库... ...

相关推荐
StrokeAce1 小时前
linux桌面软件(wps)内嵌到主窗口后的关闭问题
linux·c++·qt·wps·窗口内嵌
一颗花生米。2 小时前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
问道飞鱼2 小时前
Java基础-单例模式的实现
java·开发语言·单例模式
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
通信仿真实验室3 小时前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&3 小时前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
家有狸花4 小时前
VSCODE驯服日记(三):配置C++环境
c++·ide·vscode
dengqingrui1235 小时前
【树形DP】AT_dp_p Independent Set 题解
c++·学习·算法·深度优先·图论·dp
C++忠实粉丝5 小时前
前缀和(8)_矩阵区域和
数据结构·c++·线性代数·算法·矩阵
ZZZ_O^O5 小时前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树