Qt使用Log4qt日志系统

1、下载log4qt项目

项目地址:https://github.com/devbean/log4qt

注意:log4qt网上有多个项目,比如https://sourceforge.net/projects/log4qt/(已迁移到https://github.com/MEONMedical/Log4Qt),此项目用的人多,但是多个版本下载下来测试,都编译不过去,然后才找到上面那个项目,没有问题。

2、添加进我的项目

①创建一个qt项目;

②拷贝log4qt文件夹到项目根目录下;

③在pro文件添加:

include(log4qt/log4qt.pri)

这样就添加完成了。

3、部署设置

网上找了个文章:https://blog.csdn.net/u012532263/article/details/82835284

感谢大神把这些工作都做了。

在项目中添加类QBLog4Qt,此类基于QObject,代码如下:

①qblog4qt.h

#ifndef QBLOG4QT_H
#define QBLOG4QT_H

#include 
#include "log4qt/logger.h"
//#include "log4qt_global.h"
#include "log4qt/propertyconfigurator.h"

#define Log4Debug QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO).debug
#define Log4Info  QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO).info
#define Log4Warn  QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO).warn
#define Log4Error QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO).error
#define Log4Fatal QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO).fatal
#define Log4qt    QBLog4Helper(__FILE__, __LINE__, Q_FUNC_INFO)


class QBLog4Qt : public QObject
{
    Q_OBJECT
    LOG4QT_DECLARE_QCLASS_LOGGER

public:
    explicit QBLog4Qt(QObject *parent = 0);
    ~QBLog4Qt();

    static QBLog4Qt *instance();
    virtual void debug(const QString& log){logger()->debug(log);}
    virtual void info (const QString& log){logger()->info(log);}
    virtual void warn (const QString& log){logger()->warn(log);}
    virtual void error(const QString& log){logger()->error(log);}
    virtual void fatal(const QString& log){logger()->fatal(log);}
};


class QBLog4Helper{
    Q_DISABLE_COPY(QBLog4Helper)

public:
    Q_DECL_CONSTEXPR QBLog4Helper() : version(1), line(0), file(0), function(0) {}
    QBLog4Helper(const char *fileName, int lineNumber, const char *functionName);
    enum LogType{LGDebugMsg, LGInfoMsg, LGWarningMsg, LGErrorMsg, LGFatalMsg};

    QString TemplateParameter (){ return ""; }
    template 
    QString TemplateParameter(T head, Args ... args) { return QString("%1 ").arg(head) + TemplateParameter(args...); }

    template 
    void debug(T head, Args ... args){
        QString logmsg = QString("%1 ").arg(head) + TemplateParameter(args...);
        writelogToLocal(LGDebugMsg,logmsg);
    }

    template 
    void info(T head, Args ... args){
        QString logmsg = QString("%1 ").arg(head) + TemplateParameter(args...);
        writelogToLocal(LGInfoMsg,logmsg);
    }

    template 
    void warn(T head, Args ... args){
        QString logmsg = QString("%1 ").arg(head) + TemplateParameter(args...);
        writelogToLocal(LGWarningMsg,logmsg);
    }

    template 
    void error(T head, Args ... args){
        QString logmsg = QString("%1 ").arg(head) + TemplateParameter(args...);
        writelogToLocal(LGErrorMsg,logmsg);
    }

    template 
    void fatal(T head, Args ... args){
        QString logmsg = QString("%1 ").arg(head) + TemplateParameter(args...);
        writelogToLocal(LGFatalMsg,logmsg);
    }

    virtual void writelogToLocal(LogType logtype, const QString& logmsg);
    virtual void copy(const QBLog4Helper &logContext){}

    template 
    inline QBLog4Helper &operator<<(T logmsg) {
        writelogToLocal(LGInfoMsg,QString("%1").arg(logmsg));
        return *this;
    }

    int version;
    int line;
    const char *file;
    const char *function;
};

#endif // QBLOG4QT_H

②qblog4qt.cpp

#include "qblog4qt.h"
#include 
#include 
#include 
#include 
#include 

QBLog4Qt::QBLog4Qt(QObject *parent) :
    QObject(parent)
{
    QDir mkdir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    if(!mkdir.exists()) mkdir.mkdir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));

    //:/Users/Dione/AppData/Local/log4Test/log4qt.log
    //QString outpath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/log4qt.log";
    QString outpath = "logs/log4qt.log";// 日志改为在程序同目录下

    QString configPath = QApplication::applicationDirPath() + "/log4qt.conf";
    if(!QFile::exists(configPath)){//不存在配置文件 创建默认配配置文件
        QSettings configSet(configPath,QSettings::IniFormat);
        configSet.setIniCodec("UTF-8");
        configSet.setValue("log4j.rootLogger",QStringList()<<"INFO"<<"rollingFile");
        configSet.setValue("log4j.additivity.org.apache","true");
        configSet.setValue("log4j.appender.rollingFile","Log4Qt::RollingFileAppender");
        configSet.setValue("log4j.appender.rollingFile.ImmediateFlush","true");
        configSet.setValue("log4j.appender.rollingFile.AppendFile","true");
        configSet.setValue("log4j.appender.rollingFile.File",outpath);// 改为自己的路径
        configSet.setValue("log4j.appender.rollingFile.MaxFileSize","4096KB");
        configSet.setValue("log4j.appender.rollingFile.MaxBackupIndex","50");
        configSet.setValue("log4j.appender.rollingFile.layout","Log4Qt::PatternLayout");
        configSet.setValue("log4j.appender.rollingFile.layout.ConversionPattern","[%p] %d --> %m %n%n");
        configSet.sync();
    }else{// 存在修改日志保存路径
        QSettings configSet(configPath,QSettings::IniFormat);
        configSet.setIniCodec("UTF-8");
        configSet.setValue("log4j.appender.rollingFile.File",outpath);
        configSet.sync();
    }

    Log4Qt::PropertyConfigurator::configure(configPath);
    logger()->info("start used log4qt!");
}

QBLog4Qt::~QBLog4Qt()
{
    logger()->info("stop used log4qt!");
}

QBLog4Qt *QBLog4Qt::instance()
{
    static QBLog4Qt obj;
    return &obj;
}


QBLog4Helper::QBLog4Helper(const char *fileName, int lineNumber, const char *functionName)
       : version(1)
       , line(lineNumber)
       , file(fileName)
       , function(functionName)
{
}

void QBLog4Helper::writelogToLocal(QBLog4Helper::LogType logtype, const QString &log)
{
    QString threadText = QStringLiteral("0x%1").arg(quintptr(QThread::currentThreadId()));
    QString filter = QString("[file(%1)] [func(%2) line(%3) pid(%4)] ").arg(file).arg(function).arg(line).arg(threadText);

    switch (logtype) {
    case LGDebugMsg: QBLog4Qt::instance()->debug(filter+log);
        break;
    case LGInfoMsg: QBLog4Qt::instance()->info(filter+log);
        break;
    case LGWarningMsg: QBLog4Qt::instance()->warn(filter+log);
        break;
    case LGErrorMsg: QBLog4Qt::instance()->error(filter+log);
        break;
    case LGFatalMsg: QBLog4Qt::instance()->fatal(filter+log);
        break;
    default: QBLog4Qt::instance()->info(filter+log);
        break;
    }
}

4、使用

在代码中使用:

Log4Info("hello world log4info4!","abcdefg");

运行即可在log/log4qt.log文件中看到日志:

[INFO] 2019-06-11 17:20:48.280 --> start used log4qt! 



[INFO] 2019-06-11 17:20:48.280 --> [file(..\TestLog\mainwindow.cpp)] [func(MainWindow::MainWindow(QWidget*)) line(33) pid(0x29956)] hello world log4info4! abcdefg  



[INFO] 2019-06-11 17:21:04.113 --> stop used log4qt! 

 

你可能感兴趣的:(qt)