qt日志

main函数中加入:
qInstallMessageHandler(CLog::OutputMessage);
1.头文件

#ifndef CLOG_H
#define CLOG_H

#include <QObject>
#include <QMutex>

class CLog : public QObject
{
    Q_OBJECT

public:
    CLog(QObject* parent = nullptr);
    static void OutputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg);   // 输出日志
    static bool DeleteLogFile();    // 删除日志文件
private:
    static QMutex m_mutex;
};

#endif // CLOG_H

2.源文件

#include "clog.h"
#include <QFile>
#include <QCoreApplication>
#include <QDateTime>
#include <QTextStream>
#include <QDir>

const int day_max = 300;

QMutex CLog::m_mutex;

void CLog::OutputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QMutexLocker lock(&m_mutex);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString text = QString("[%1]%2").arg(current_date_time).arg(msg);

    QString path = QCoreApplication::applicationDirPath() + "/log/";
    QDir dir(path);
    if(!dir.exists()) {
        dir.mkpath(path);
    }
    QFile file(path + "log.txt");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Append)) {
        return;
    }
    QTextStream stream(&file);
    stream << text << endl;
    file.flush();
    file.close();
}

bool CLog::DeleteLogFile()
{
    QString path = QCoreApplication::applicationDirPath() + "/log/log.txt";
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly)) {
        return false;
    }
    char buff[64];
    memset(buff, 0, 64);
    file.readLine(buff, 64);
    file.close();

    QString data = QString(buff);
    int pos = data.indexOf("]");
    if(pos == -1 || pos < 4) {
        return false;
    }
    data = data.mid(1, pos - 1);
    QDateTime start = QDateTime::fromString(data, "yyyy-MM-dd hh:mm:ss");
    QDateTime currentTime =  QDateTime::currentDateTime();
    auto days = start.daysTo(currentTime);
    if(days > day_max) {
        QFile::remove(path);
    }
    return true;
}

CLog::CLog(QObject* parent) :QObject(parent)
{

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 将Qt日志输出到安卓日志系统里 因为在学习qt on android,所以想把Qt日志输出到安卓日志系统里,方便程...
    技术喵阅读 492评论 0 1
  • QT有自己的日志打印函数族,通常我们使用qDebug()、qInfo()、qCritical()输出程序的工作日志...
    大匡先生阅读 1,277评论 0 1
  • 界面 主窗口界面设计 标题栏:直接设Window-Title属性;Window-icon属性可加图标。底部状态栏:...
    码园老农阅读 3,801评论 1 13
  • 在Qt中使用日志 Qt提供了5个全局函数用于输出调试或警告信息。 qDebug:调试信息 qWarning:警告信...
    技术喵阅读 5,007评论 0 1
  • 第一章 计算机与C++编程简介 C++程序6个阶段编程 ->预处理->编译->连接->装入->执行1.程序在编译器...
    rogertan30阅读 4,052评论 0 1