Qt 日志控制台文本切换

debug控制台打印信息;release文本查看信息

main函数外:

void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 加锁
    static QMutex mutex;
    mutex.lock();

    QByteArray localMsg = msg.toLocal8Bit();

    QString strMsg;
    switch((int)type)
    {
    case QtDebugMsg:
        strMsg = QString("Debug:");
        break;
    case QtWarningMsg:
        strMsg = QString("Warning:");
        break;
    case QtCriticalMsg:
        strMsg = QString("Critical:");
        break;
    case QtFatalMsg:
        strMsg = QString("Fatal:");
        break;
    }

    // 设置输出信息格式
    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString strMessage = QString(strMsg+"%1 File:%2  Line:%3  Function:%4  DateTime:%5")
                         .arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function).arg(strDateTime);

    // 输出信息至文件中(读写、追加形式)
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("yyyy-MM-dd");
    QString filename = QCoreApplication::applicationDirPath() + "/log/" + current_date + ".txt";
    QFile file(filename);
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << strMessage << "\r\n";
    file.flush();
    file.close();

    // 解锁
    mutex.unlock();
}

main函数里面:

    //建立log文件夹
    QDir *temp = new QDir;
    QString s = "/log/";
    QString filedir = QCoreApplication::applicationDirPath() + s;
    bool exist = temp->exists(filedir);
    if(!exist)
    {
        temp->mkpath(filedir);
    }
    delete temp;
#ifdef QT_NO_DEBUG
       qInstallMessageHandler(MessageOutput);
#else
    qSetMessagePattern("[%{time yyyyMMdd h:mm:ss t} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}");
#endif

注意:1、要取消控制台需要:去掉终端 注释CONFIG += console

在这里插入图片描述
2、解决release打印信息为空的BUG
图片来源于网络

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值