在QT中使用日志系统

文章转载自 https://blog.csdn.net/weixin_42542969/article/details/88836449

当写好的软件发布出去后,用户遇到死机或一些其他的bug,我们该怎么追踪这些问题呢,这时候日志系统很好的帮助了我们。

*我在原作者的基础上增加了日志输出模式的区分,开发阶段需要看到所有日志,而发布版只需要看错误日志就行了,所以在这里加以分别。

#define compileMode 2 //控制日志的输出模式: 1.debug; 2.release

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    QString message;
    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QFile file("log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);

    if(compileMode == 1){
        switch(type){
            case QtDebugMsg:
                text = QString("Debug:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
            case QtWarningMsg:
                text = QString("Warning:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
            case QtCriticalMsg:
                text = QString("Critical:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
            case QtFatalMsg:
                text = QString("Fatal:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
        }
    }
    else if(compileMode == 2){
        switch(type){
            case QtCriticalMsg:
                text = QString("Critical:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
            case QtFatalMsg:
                text = QString("Fatal:");
                message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
                break;
        }
    }    

    if(message != ""){
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        file.flush();
        file.close();
    }
    mutex.unlock();
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值