Qt 将qDebug重定向到文本文件

在qt的使用过程中,开发者通常使用qDebug, qInfo, qWarning输出控制台信息。且qt提供直接通过qDebug等方法将信息输出到文本文件的方法。又因为qDebug本身线程安全,因此在使用的过程中能够减少开发者在多线程数据处理的负担。

关于将qDebug信息重定向到文本的示例如下:

void writeToLog(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
    QString prefix;
    switch (type) {
        case QtDebugMsg:
            prefix = "Debug";
            break;
        case QtInfoMsg:
            prefix = "Info";
            break;
        case QtWarningMsg:
            prefix = "Warning";
            break;
        case QtCriticalMsg:
            prefix = "Critical";
            break;
        case QtFatalMsg:
            prefix = "Fatal";
            break;
    }
    QString fileName = "run_" + QDateTime::currentDateTime().toString("yyyyMMdd") + ".log";
    QFile logFile(QApplication::applicationDirPath() + LOG + fileName);
    if (logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        QTextStream out(&logFile);
        out << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "] "
            << "[" << prefix << "] "
            << context.category << ": "
            << msg << " (" << context.file << ":" << context.line << ")\n";
        logFile.close();
    }

    // 对于QtFatalMsg,确保标准处理被执行(默认是终止程序)
    if (type == QtFatalMsg)
        abort();
}

int main(int argc, char **argv) {
    QApplication a(argc, argv);

    qInstallMessageHandler(writeToLog);

    // TODO: 初始化自己的窗口或进行其他操作

    return QApplication::exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值