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. 没有日志缓冲,直接写文件,性能会有问题

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

相关推荐
AA陈超38 分钟前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻
mit6.8241 小时前
[Meetily后端框架] AI摘要结构化 | `SummaryResponse`模型 | Pydantic库 | vs marshmallow库
c++·人工智能·后端
screenCui1 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
R-G-B1 小时前
【02】MFC入门到精通——MFC 手动添加创建新的对话框模板
c++·mfc·mfc 手动添加创建新的对话框
linux kernel1 小时前
第七讲:C++中的string类
开发语言·c++
Tipriest_2 小时前
[数据结构与算法] 优先队列 | 最小堆 C++
c++·优先队列·数据结构与算法·最小堆
玩代码2 小时前
Java线程池原理概述
java·开发语言·线程池
宛西南浪漫戈命2 小时前
Centos 7下使用C++使用Rdkafka库实现生产者消费者
c++·centos·linq
泰勒疯狂展开2 小时前
Java研学-MongoDB(三)
java·开发语言·mongodb
zzywxc7872 小时前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。
java·大数据·开发语言·人工智能·spring·重构·prompt