Qt 学习 第2节 日志输出和保存

来源:互联网 发布:先导者之爱知重生 编辑:程序博客网 时间:2024/05/01 18:39
重载 outputMessage (注意Qt4和Qt5有点不同)
#ifndef Qt_5
//===Qt4
DebuggerPrinter printer;
void outputMessage(QtMsgType type,const QMessageLogContext &context, QString &msg)
{
    static QMutex mutex;
    mutex.lock();
    printer.printDebug(type, QString(msg));
    mutex.unlock();
}
#else
//Qt5
void outputMessage(QtMsgType type,
                   const QMessageLogContext &context,
                   const QString &msg)
{
    static QMutex mutex;
    mutex.lock();
    printer.printDebug(type, msg);
    mutex.unlock();
}
#endif
void MainWindow::printDebug(int type, QString text)
{
    switch (type) {
    case QtDebugMsg:
//        this->ui->textBrowser->setTextColor(Qt::magenta);
        this->ui->textBrowser->setTextColor(Qt::darkGreen);
        break;
    case QtWarningMsg:
        this->ui->textBrowser->setTextColor(Qt::yellow);
        break;
    case QtCriticalMsg:
        this->ui->textBrowser->setTextColor(Qt::red);
        break;
    case QtFatalMsg:
        this->ui->textBrowser->setTextColor(Qt::darkRed);
        break;
    default:
        break;
    }
    this->ui->textBrowser->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                                  + ":" +text);
}

void MainWindow::save_log()
{
    QDir tmp;
    if(!tmp.exists(QCoreApplication::applicationDirPath()+"/log"))
    {
        if(!tmp.mkdir(QCoreApplication::applicationDirPath()+"/log"))
        {
            QMessageBox::warning(this,tr("警告"),tr("创建目录log失败"),tr("确认"));
            return;
        }
    }
    QString file_path =QCoreApplication::applicationDirPath() + QString("/log/%1.txt").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss"));
//    QString file_path = QString("log/log.txt");
    QFile file(file_path);
    if(!file.open(QIODevice::WriteOnly | QFile::Text))
    {
        qDebug()<<"open"<<file_path<<"失败";
        return;
    }else
    {
        QTextStream out(&file);
        out<<this->ui->textBrowser->toPlainText()<<endl;
        file.flush();
        file.close();
        this->ui->textBrowser->clear();
    }
}
//===========大于一万行自动保存
void MainWindow::slot_auto_save_log()
{
    if(this->ui->textBrowser->document()->blockCount() >= 10000)
    {
        save_log();
    }
}
//===========退出自动保存
void MainWindow::on_action_clear_log_triggered()
{
    save_log();
}