1.下载
github地址:https://github.com/MEONMedical/Log4Qt(支持Qt5版本)
要求是5.12,但下载Log4Qt 1.5.1版本可以支持QT5.9
2.解压编译
解压出来后
用QTCreator 打开log4qt.pro
执行Qmake
构建工程
在构建好的目录里会生成log4qt.lib和log4qt.dll文件
3.QT .PRO引用
.PRO
INCLUDEPATH+= C:\Users\94414\Downloads\Log4Qt-1.5.1\Log4Qt-1.5.1\src
INCLUDEPATH+= C:\Users\94414\Downloads\Log4Qt-1.5.1\Log4Qt-1.5.1\src\log4qt
INCLUDEPATH+= C:\Users\94414\Downloads\Log4Qt-1.5.1\Log4Qt-1.5.1\include
INCLUDEPATH+= C:\Users\94414\Downloads\Log4Qt-1.5.1\Log4Qt-1.5.1\include\log4qt
LIBS+= C:\Users\94414\Downloads\Log4Qt-1.5.1\build-log4qt-Desktop_Qt_5_9_5_MSVC2015_64bit-Release\bin\log4qt.lib
4.main.cpp
引用头文件
#include <logmanager.h>
#include <propertyconfigurator.h>
/*!
* \brief 初始化配置log4Qt参数
*/
void initLogConfig()
{
//log4j.rootLogger日志输出类别和级别:只输出不低于该级别的日志信息DEBUG < INFO < WARN < ERROR < FATAL
//[%l]可打印代码行数
//log4j.rootLogger = DEBUG,Console,File //同时输出控制台和File
QString logString = "log4j.rootLogger = DEBUG,Console,File\n"
"log4j.appender.Console = org.apache.log4j.ConsoleAppender\n"
//"log4j.appender.Console.Encoding=UTF-8\n"
"log4j.appender.Console.layout=org.apache.log4j.PatternLayout\n"
"log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n \n"
"log4j.appender.File = org.apache.log4j.FileAppender\n"
"log4j.appender.File = org.apache.log4j.DailyFileAppender\n"
//"log4j.appender.File = org.apache.log4j.RollingFileAppender\n"
//"log4j.appender.File.Encoding=UTF-8 \n"
"log4j.appender.File.File = C:/Log/infoLog.txt\n"
//"log4j.appender.File.MaxFileSize = 10MB\n"
"log4j.appender.File.AppendFile = true\n"
"log4j.appender.File.Threshold = WARN\n"
"log4j.appender.File.layout = org.apache.log4j.PatternLayout\n"
"log4j.appender.File.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%c] [%p] --> %m%n \n";
QFile file( QCoreApplication::applicationDirPath()+"log4qt.conf");
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.write(logString.toUtf8());
file.close();
//配置文件路径
Log4Qt::PropertyConfigurator::configure(QCoreApplication::applicationDirPath()+"log4qt.conf");
//QDebug 输出到Log
Log4Qt::LogManager::setHandleQtMessages(true);
// QLoggingCategory::defaultCategory()->setEnabled(QtDebugMsg, true);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
initLogConfig();//log4qt日志
MainWindow w;
w.show();
return a.exec();
}
单独运行需要加Qt5network.dll
5.效果
可以在QT终端console和txt文件输出qDebug、qWarning等信息。
6.小问题
1.console端中文乱码,改utf-8,gbk ,都无效。
改QT设置的utf-8+无BOM好像还导致了QT中文识别编译不过的问题=_=!
最后都用英文。。