Qt将打印信息输出到文件
将打印信息(qDebug、qInfo、qWarning、qCritial等)输出到指定文件来以实现简单的日志功能。
#include "mainwindow.h"
#include <QApplication>
#include <QLoggingCategory>
#include <QMutex>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
QString logDirName = "log";
QMutex mutex;
void logInit();
void message(QtMsgType type, const QMessageLogContext &context, const QString &msg);
int main(int argc, char *argv[])
{
logInit();
QApplication a(argc, argv);
qDebug()<<"aaaa";
MainWindow w;
w.show();
return a.exec();
}
void logInit()
{
QDir dir(logDirName);
// 不存在log目录就先创建
if (!dir.exists()) QDir().mkdir(logDirName);
// 遍历日志目录所有日志文件,然后删除十天前的日志文件
QFileInfoList logList = dir.entryInfoList({"*.txt"}, QDir::Files, QDir::Time);
foreach (const QFileInfo &info, logList) {
if (info.created().daysTo(QDateTime::currentDateTime()) > 10) dir.remove(info.fileName());
}
QLoggingCategory::setFilterRules("*.info=true\n");
qInstallMessageHandler(message);
}
void message(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
mutex.lock();
QString text = QString();
switch (type) {
case QtDebugMsg:
text = "Debug";
break;
case QtWarningMsg:
text = "Warning";
break;
case QtCriticalMsg:
text = "Critical";
break;
case QtInfoMsg:
text = "Info";
break;
case QtFatalMsg:
text = "Fatal";
break;
default:
break;
}
QString log
= QString("[%1:%2:%3:%4]%5:%6").arg(QDateTime::currentDateTime().toString(
"yyyy-MM-dd hh:mm:ss.zzz")).arg(context.file).arg(
context.function).arg(context.line).arg(text).arg(msg);
static QString path = QDir::cleanPath(
logDirName+QDir::separator()+QDateTime::currentDateTime().toString(
"yyyyMMdd-hhmmsszzz")+QString("LOG.txt"));
QFile file(path);
if (file.open(QIODevice::WriteOnly|QIODevice::Append)) {
QTextStream stream(&file);
stream<<log<<endl;
file.flush();
file.close();
}
mutex.unlock();
}
该项目内所有打印信息将会输出到指定文件,比如在主界面mainwindow中点击按钮印一句d
void MainWindow::on_pushButton_clicked()
{
qDebug()<<"11111";
}
程序运行后,不停点击按钮,可以看到有生成对应文件