log4qt是log4j在QT框架下的移植。本文将简述如何快速的将log4qt部署到自己的QT项目中来。
官方地址:http://log4qt.sourceforge.net/
1. 下载log4qt
地址:https://sourceforge.net/projects/log4qt/files/Log4Qt/0.3/
2. 解压
使用到的是log4qt-0.3\log4qt\src\log4qt目录,下面包含了所需的头文件和实现文件。
3. 添加log4qt文件到我们已有的工程中(以工程test_proj为例)
拷贝目录到test_proj
比如D:\qt_workspace\test_proj\log4qt
4. 配置test_proj.proj文件
编译整个工程,生成test_proj.proj
在已生成的test_proj.proj文件中添加:
DEPENDPATH += . log4qt log4qt/helpers log4qt/spi log4qt/varia
INCLUDEPATH += . log4qt log4qt/helpers log4qt/spi log4qt/varia
5. main.cpp文件中引入log4j配置文件
#include <QCoreApplication>
#include "log4qt/propertyconfigurator.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Log4Qt::PropertyConfigurator::configure(a.applicationDirPath()+ "/log4j.properties");
//your code
return a.exec();
}
6. 类头文件中引入LOG4QT_DECLARE_QCLASS_LOGGER宏定义
class function : public QObject
{
Q_OBJECT
LOG4QT_DECLARE_QCLASS_LOGGER
public:
founction();
};
7. 实现文件中使用方法
logger()->info("hello world!");
8. log4j.properties配置文件
#### Use two appenders, one to log to console, another to log to a file
log4j.rootLogger=INFO,stdout,R1
log4j.addivity.org.apache=true
#### First appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p (%t) %c (%M:%L)] - %m%n
#### Second appender writes to a file
log4j.appender.R1=org.apache.log4j.RollingFileAppender
#2021-08-24遇到大坑,前来补充。appendFile很关键
#软件重启后:true表示追加写入,false覆盖写入,默认值false
log4j.appender.R1.appendFile=true
log4j.appender.R1.File=log/test.log
# Control the maximum log file size
log4j.appender.R1.MaxFileSize=1000KB
# Archive log files (one backup file here)
log4j.appender.R1.MaxBackupIndex=10
log4j.appender.R1.layout=org.apache.log4j.PatternLayout
log4j.appender.R1.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p (%t) %c (%M:%L)] - %m%n