QT日志功能

10 篇文章 1 订阅

先看一下最终效果:在一个叫做“Log”的目录下会生成以当前时间命名的日志文件。

 下面来看一下实现方法:

先创建一个最简单的qt工程,如下图所示,想必大家都非常熟悉

 将下面两个文件加入工程中:

log.h:


#pragma once

#include <QMutex>
#include <QString>

#define LOG_FILE_NAME QString(".\\Log\\") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + QString(".log")

static int s_logLevel = 0;
static QMutex s_logMutex;
static QString s_logPath;

void setLogPath(const QString &path);
void setLogLevel(int level);
void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg);

log.cpp:

#include "Log.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextStream>
#include <QDateTime>

void setLogPath(const QString & path)
{
    s_logPath = path;
}

void setLogLevel(int level)
{
    s_logLevel = level;
}

bool static ensureDirExist(const QString &dirPath)
{
    QDir dir(dirPath);
    if (dir.exists())
    {
        return true;
    }

    return dir.mkpath(dirPath);
}

void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
    if (type < s_logLevel)
    {
        return;
    }

    QString logInfo;
    QString logTime = QDateTime::currentDateTime().toString("hh-mm-ss-MM-dd-yyyy");
    switch (type)
    {
    case QtDebugMsg:
        logInfo = QString("%1 [Debug] %2").arg(logTime, msg);
        break;

    case QtWarningMsg:
        logInfo = QString("%1 [Warning] %2").arg(logTime, msg);
        break;

    case QtCriticalMsg:
        logInfo = QString("%1 [Critical] %2").arg(logTime, msg);
        break;

    case QtFatalMsg:
        logInfo = QString("%1 [Fatal] %2").arg(logTime, msg);
        abort();
//    case QtInfoMsg:
//        logInfo = QString("%1 [Info] %2").arg(logTime, msg);
//        break;
    }

    s_logMutex.lock();
    QFile outFile(s_logPath);
    QFileInfo fileInfo(outFile);
    if (!ensureDirExist(fileInfo.absoluteDir().absolutePath()))
        return;

    if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        return;

    QTextStream ts(&outFile);
    ts << logInfo << endl;
    outFile.close();
    s_logMutex.unlock();
}

加完之后目录结构如下图所示:

 让我们来试一试吧,

在main.cpp中加入如下代码:

运行一下,可以看到Log文件夹下生成了日志,结束。

目前只是知道可以这样子做,后面有空再仔细学习一下代码。

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值