日志类封装

#ifndef MYMETHOD_H
#define MYMETHOD_H
#include <mutex>
class Mymethod
{
public:
    Mymethod();
    static void record(QString info,Print_Type type=PRINT_NORMAL);
private:
    static std::mutex mtxLog;
};

enum Print_Type{

PRINT_NORMAL=0,

PRINT_OK,

PRINT_WARN,

PRINT_ERR,

PRINT_INFO

};



#endif // MYMETHOD_H
/*****************************************************************/
//作者:朱小勇
//函数名称:record
//函数参数:NULL
//函数返回值:NULL
//函数作用:NULL
//备注:NULL
/*****************************************************************/
std::mutex Mymethod::mtxLog;
void Mymethod::record(QString info,Print_Type type)
{
    QString str=Mymethod::getCurentTimeStr(false);
    if(PRINT_INFO==type || PRINT_NORMAL==type)
    {
        str += QString(SPACE_4)+"info";
    }
    else if(PRINT_OK == type)
    {
        str += QString(SPACE_4)+"ok";
    }
    else if(PRINT_WARN == type)
    {
        str += QString(SPACE_4)+"warn";
    }
    else if(PRINT_ERR == type)
    {
        str += QString(SPACE_4)+"err";
    }
    str += QString(SPACE_4)+info;

#if OPEN_IF//直接打印
    qDebug()<<str;
#endif

#ifdef DEBUG_TO_FILE//将调试信息写入日志文件
    static QString logPath="";
    str = str+"
";
    if(logPath=="")
    {
        logPath = "./"+QDateTime::currentDateTime().toString("yyMMddhhmmss")+".log";
    }
    {
        std::unique_lock<std::mutex> mtxLog;
        QFile file(logPath);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            qDebug()<<"***waning***,log file create failed.";
            return;
        }
        if(file.size()>LOG_MAX_SIZE)
        {
            file.close();
            logPath = "./"+QDateTime::currentDateTime().toString("yyMMddhhmmss")+".log";
            file.setFileName(logPath);
            if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
            {
                qDebug()<<"***waning***,log file create failed.";
                return;
            }
        }
        if(VALUE__1==file.write(str.toLatin1()))
        {
            qDebug()<<"***waning***,log write failed.";
        }
        file.close();
    }
#endif
}
原文地址:https://www.cnblogs.com/judes/p/11905935.html