把Qt中qDebug输出信息和警告信息写入文件

本文介绍了如何在Qt程序中使用qDebug函数记录不同级别的调试信息,并将其输出到文件,以便于问题追踪。同时,展示了如何安装自定义消息处理器来控制终端窗口的警告信息显示。
摘要由CSDN通过智能技术生成

在工作中要打印qDebug信息和终端窗口中的警告信息,方便进行问题追踪和调试。

直接上测试代码:

void MyMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString logText;
    // 选择日志级别,并构造日志文本
    switch (type) {
    case QtDebugMsg:
        logText = QString("[Debug]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
        break;
    case QtInfoMsg:
        logText = QString("[Info]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
        break;
    case QtWarningMsg:
        logText = QString("[Warning]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
        break;
    case QtCriticalMsg:
        logText = QString("[Critical]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
        break;
    case QtFatalMsg:
        logText = QString("[Fatal]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
        break;
    default:
        break;
    }
    // 写入日志文件
    QFile logFile("./debug.txt");
    logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    QTextStream textStream(&logFile);
    textStream << logText << endl;
    logFile.close();
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qInstallMessageHandler(MyMessageOutput);
    //多线程测试
    MyThread thread;
    thread.Open();
    thread.start();
    return a.exec();
}

程序运行之后,在终端上将不会有输出信息。只有当程序异常退出之后,终端窗口上会有一个退出提示。运行结果如下:

参考链接:

QDebug 自定义信息输出到文件_qdebug输出到文件-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_41350775/article/details/131461124

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值