//头文件(文件夹log4cxx)、log4cxx.lib、log4cxx.dll、log4cxx.properties
1.设置配置文件log4cxx.properties
2.使用头文件,命名空间
#include "log4cxx/propertyconfigurator.h"
using namespace log4cxx;
3.在Qt中可以使用qInstallMessageHandler自定义消息处理
例子:
#include "mainwindow.h"
#include <QApplication>
#include "log4cxx/propertyconfigurator.h"
#include <QDebug>
#include <QDate>
#include <iostream>
using namespace std;
using namespace log4cxx;
LoggerPtr g_pAppLog = nullptr;
void OutputMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QString strDetail = QString("%1-%2, %3 ").arg(QString(context.file), QString::number(context.line), msg);
switch (type)
{
default:
LOG4CXX_DEBUG(g_pAppLog, strDetail.toUtf8().constData());
break;
case QtWarningMsg:
LOG4CXX_WARN(g_pAppLog, strDetail.toUtf8().constData());
break;
case QtFatalMsg:
LOG4CXX_ERROR(g_pAppLog, strDetail.toUtf8().constData());
break;
case QtInfoMsg:
LOG4CXX_INFO(g_pAppLog, strDetail.toUtf8().constData());
break;
}
cout << QDateTime::currentDateTime().toString("yyyy-MM:dd hh:mm:ss").toStdString() << " " << string(msg.toLocal8Bit()) << endl;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
/*****************设置log打印日志*************************/
QString strConfigPath = QCoreApplication::applicationDirPath() + "/log4cxx.properties";
PropertyConfigurator::configure(strConfigPath.toUtf8().constData());
g_pAppLog = Logger::getLogger("main");
qInstallMessageHandler(OutputMessageHandler);
MainWindow w;
w.show();
return a.exec();
}