Qt日志重定向及内置类型告警屏蔽

在Qt中,使用qInstallMessageHandler()可以设置自定义的日志处理函数,例如myMessageOutput(),该函数将Qt的消息输出到文件log.txt中,并可按需过滤特定类型的日志,如屏蔽QtDebugMsg。示例代码展示了如何实现这一功能。
摘要由CSDN通过智能技术生成

在Qt中,可以通过qInstallMessageHandler()函数来实现日志重定向。该函数需要传入一个指向函数的指针,该函数将被用于处理Qt的日志消息。 以下是一个示例代码,演示如何将Qt的日志消息输出到一个文件中:

#include <QCoreApplication>
#include <QFile>
#include <QDebug>

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        abort();
    }
    
    // 将日志消息输出到文件中
    QFile outFile("log.txt");
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&outFile);
    ts << msg << endl;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    // 将日志消息重定向到自定义函数
    qInstallMessageHandler(myMessageOutput);
    
    // 输出一些日志消息
    qDebug() << "This is a debug message.";
    qInfo() << "This is an info message.";
    qWarning() << "This is a warning message.";
    qCritical() << "This is a critical message.";
    qFatal("This is a fatal message.");
    
    return a.exec();
}

在上面的示例代码中,我们定义了一个名为myMessageOutput()的函数,该函数将被用于处理Qt的日志消息。在该函数中,我们首先将日志消息输出到标准错误流中,然后将日志消息追加到一个名为log.txt的文件中。

可以通过这种方法,屏蔽qt内置类型的一些输出,使控制台更加清爽。比如要屏蔽qt内置类型如QLayout等的调试信息输出。代码示例如下:

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    Q_UNUSED(context);
    Q_UNUSED(msg);
    // 取消输出 QtDebugMsg 类型的告警信息
    if (type == QtDebugMsg)
        return;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zw_ggr_2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值