Qt 自定义日志输出函数(按照年月日路径)

1. 前言

Qt 实现的日志函数, 可以按照日期年月日路径生成文件并记录日志

2. 效果

3. 源码

main.cpp

​

#include 
#include 
#include 
#include 
#include 
#include 
#include 

QMutex LogLock;

int WriteLog(QString type, QString content)
{
    LogLock.lock();

    QDateTime currentTime = QDateTime::currentDateTime();

    QString time = currentTime.toString("yyyy-MM-dd hh:mm:ss");
    QString date= currentTime.toString("yyyyMMdd");
    QString month = date.mid(4, 2);
    QString year=date.mid(0, 4);
    QString day = date.mid(6, 2);

    QString path="Logs/"+ year + "/" + month+"/" + day + "/";

    QString fileName = path + type + "_"+date + ".log";
    QString data = "[" + time + "]" + " " + content;

    QDir dir;
    if (! (dir.exists(path)))
        dir.mkpath(path);

    QFile f(fileName);
    f.open(QIODevice::WriteOnly|QIODevice::Append) ;
    QTextStream t(&f);
    t << data<< endl;
    f.close();

    LogLock.unlock();
    return 0;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    WriteLog("Log", "content");

    return a.exec();
}

[点击并拖拽以移动]
​

 

你可能感兴趣的:(Qt)