您的位置:首页 > 编程语言 > Qt开发

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

2017-10-21 15:52 260 查看
重载 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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: