简单的Qt log类 直接使用

简单的Qt log类 直接使用

Mylog_.h

#ifndef MYLOG__H
#define MYLOG__H

#include <QObject>

class MyLog_ : public QObject
{
    Q_OBJECT
public:
    explicit MyLog_(QObject *parent = nullptr);

    //1.创建log 失败返回0
    static bool createLogFile(QString path);

    //2.信息写入日志
    static void writeLog_(QString filePath,QString str);


};

#endif // MYLOG__H




Mylog_.cpp


#include "mylog_.h"

#include <QFile>
#include <QDir>
#include <QDebug>
#include <QDateTime>
MyLog_::MyLog_(QObject *parent) : QObject(parent)
{

}

bool MyLog_::createLogFile(QString path)
{
    if(path.isEmpty())
    {
        qDebug()<<"path is empty";
        return false;
    }
    QFileInfo f(path);
    if(f.exists())
    {
        qDebug()<<" file is exists";
        return false;
    }

    QFile file(path);
    if(!file.open(QFile::WriteOnly | QFile::Append))
    {

        qDebug()<<"file open failed";
        return false;
    }


    return true;

}

void MyLog_::writeLog_(QString filePath,QString str)
{
    if(filePath.isEmpty())
        return;

    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    QFile file(filePath);
    if(!file.open(QFile::WriteOnly | QFile::Append))
    {

        qDebug()<<"file open failed";
        return ;
    }
    QTextStream textStream(&file);

    time = time + " "+str;

    textStream<<time<<"\r\n";

    file.flush();

    file.close();
}


功能比较简单简单的Qt log类 直接使用