qt里面用log4qt日志库

时间:2022-08-30 01:17:01

1,下载链接,

项目地址:GitHub - devbean/log4qt: Logger for Qt.
注意:log4qt网上有多个项目,比如Log4Qt - Logging for C++/Qt download | SourceForge.net(已迁移到GitHub - MEONMedical/Log4Qt: Log4Qt - Logging for the Qt cross-platform application framework),此项目用的人多,但是多个版本下载下来测试,都编译不过去,然后才找到上面那个项目,没有问题。

2,使用方式

2.1编译成第三方库,在此不做介绍,自行百度

2.2 把它作为自己源代码继承进来

# 定义所需的宏
DEFINES += LOG4QT_LIBRARY

## 定义 Log4Qt 源码根目录
LOG4QT_ROOT_PATH = $$PWD/Log4Qt-master

# 指定编译项目时应该被搜索的 #include 目录
INCLUDEPATH += $$LOG4QT_ROOT_PATH/src \
               $$LOG4QT_ROOT_PATH/src/log4qt \
               $$LOG4QT_ROOT_PATH/include \
               $$LOG4QT_ROOT_PATH/include/log4qt

## 将 Log4Qt 源代码添加至项目中
include($$LOG4QT_ROOT_PATH/src/log4qt/log4qt.pri)
include($$LOG4QT_ROOT_PATH/build.pri)
include($$LOG4QT_ROOT_PATH/g++.pri)

3,代码使用,比如

//Log4Qt的使用
    QString outpath = QCoreApplication::applicationDirPath() + "/xxx.log";
    QString configPath = QApplication::applicationDirPath() + "/xxx.conf";
    if(QFile::exists(outpath) && QFile::exists(configPath))
    {
        QFile::remove(outpath);
        QFile::remove(configPath);

    }
    if(!QFile::exists(configPath)){//不存在配置文件 创建默认配配置文件
        QSettings configSet(configPath,QSettings::IniFormat);
        configSet.setIniCodec("UTF-8");
      
        configSet.setValue("log4j.rootLogger",QStringList()<<"DEBUG"<<"A2");
        //file
        //configSet.setValue("log4j.logger.A2","A2");
        configSet.setValue("log4j.appender.A2","org.apache.log4j.FileAppender");
        configSet.setValue("log4j.appender.A2","org.apache.log4j.RollingFileAppender");
        configSet.setValue("log4j.appender.A2.File",outpath);
        configSet.setValue("log4j.appender.A2.AppendFile","true");
        configSet.setValue("log4j.appender.A2.MaxFileSize","4096KB");
        configSet.setValue("log4j.appender.A2.MaxBackupIndex","3");
        configSet.setValue("log4j.appender.A2.layout","org.apache.log4j.PatternLayout");
        configSet.setValue("log4j.appender.A2.layout.ConversionPattern","%d{yyyy-MM-dd HH:mm:ss} %m%n");
        configSet.sync();
    }else{// 存在修改日志保存路径
        QSettings configSet(configPath,QSettings::IniFormat);
        configSet.setIniCodec("UTF-8");
        configSet.setValue("log4j.appender.A2.File",outpath);
        configSet.sync();
    }

    Log4Qt::PropertyConfigurator::configure(configPath);
    Log4Qt::LogManager::setHandleQtMessages(true);
    qDebug("start used log4qt!");