【qt】保存debug到log里

新建一个log.h

#ifndef LOG_H
#define LOG_H

#include 
#include 
#include 
#include 
#include 

//选择屏幕打印还是输出到文件可以根据这个宏控制或者控制函数调用位置都可以
//#define _DEBUG
//默认调试级别为warning,即小于warning级别的都不会写入日志文件
//只有release版本的时候,才会输出到日志,debug版本正常输出到终端。
namespace QT_LOG
{
//默认文件名为当前时间命名的log文件
static int m_logLevel = 1;
static QString m_logFile = QString("./log/%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
QMutex m_logMutex;

void createLOG(){
    QString logFolderPath = QDir::currentPath() + "/log";
    QDir logFolder(logFolderPath);
    if(!logFolder.exists()){
        logFolder.mkpath(logFolderPath);
    }
}

void debugMsgHandler(QtMsgType type , const QMessageLogContext &context , const QString &msg)
{
    //设置输出日志级别,小于该级别,将不会写入日志文件,默认是warning级别,即debug信息不会写入日志文件
    if (type < m_logLevel) {
        return;
    }

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

    case QtWarningMsg:
        return;
        log_info = QString("%1[Warning]:").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        break;

    case QtCriticalMsg:
        log_info = QString("%1[Critical]:").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        break;

    case QtFatalMsg:
        log_info = QString("%1[Fatal]:").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        abort();

    case QtInfoMsg:
        log_info = QString("%1[Info]:").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        break;
    }
    log_info += QString(context.file) + QString(context.line) + QString("%1").arg(msg);

    //为了线程安全
    m_logMutex.lock();

    createLOG();
    QFile outFile(m_logFile);
    if (outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        QTextStream ts(&outFile);
        ts << log_info << Qt::endl;
    }

    outFile.close();
    m_logMutex.unlock();
}

//默认调试级别为warning及以上才会写入日志文件,默认log文件名为程序启动时间命名的log文件
void logInit(QString logFile = "", int logLevel = 0)
{
#ifndef _DEBUG  //实现debug版本的时候,输出到终端;release版本的时候输出到日志文件
    if ((logLevel < 0) || (logLevel > 3)) {
        m_logLevel = 1;
    }
    else {
        m_logLevel = logLevel;
    }

    if (!logFile.isEmpty()) {
        m_logFile = logFile;
    }

    qInstallMessageHandler(debugMsgHandler);
#endif
}
}

#endif // LOG_H

在main.cpp使用

#include "widget.h"
#include 
#include "log.h" //导入接口

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

    QT_LOG::logInit(); //使用日志保存功能

    Widget w;
    w.show();
    return a.exec();
}

你可能感兴趣的:(qt)