log4cpp 是比较普遍使用的开源日志记录模块。目前有各种平台下的版本,可用于JAVA、C++、C#等各种开发语言。。本文重点详细说明在Linux 下C++开发示例。
示例中,举例了同时对两个日志对象进行了说明。注意其中的: appender1、appender2,A1、A2的定义之处。
[log4cpp]
rootCategory=DEBUG,appender1
additivity.rootCategory=false
appender.appender1=RollingFileAppender
appender.appender1.fileName=/home/log/logTrafficControlServer.log
appender.appender1.maxFileSize=10485780
appender.appender1.maxBackupIndex=10
appender.appender1.layout=PatternLayout
appender.appender1.layout.ConversionPattern=$%5p %d{%Y-%m-%d %H:%M:%S.%l}@%m%n
category.A1=DEBUG,appender1
additivity.A1=false
appender.appender2=RollingFileAppender
appender.appender2.fileName=/home/log/logTrafficControlServer_TimerDataTrans.log
appender.appender2.maxFileSize=10485780
appender.appender2.maxBackupIndex=10
appender.appender2.layout=PatternLayout
appender.appender2.layout.ConversionPattern=$%5p %d{%Y-%m-%d %H:%M:%S.%l}@%m%n
category.A2=DEBUG,appender2
additivity.A2=false
/*
* CLogOper.h
*
* Created on: 2022-02-16
* Author:
*/
#ifndef LOGMODULE_LOGRECORD_H
#define LOGMODULE_LOGRECORD_H
class CLogRecord {
public:
CLogRecord();
virtual ~CLogRecord();
public:
void GetLogFileName(const char* pszLogFileDir, const char* pszDeviceCode,
int iFileNum, char* pszLogFileName);//获得日志的文件名
/*! \fn bool CLogRecord::SetConfigureFile(const char* pszConfigureFileName, const char* pszInstanceName, const char* pszLogFileName, int iMaxFileSize, int iMaxBackupIndex, const char* pszPriority)
* \brief 设置日志配置文件
* \param[in] pszConfigureFileName
* \param[in] pszInstanceName
* \param[in] pszLogFileName
* \param[in] iMaxFileSize
* \param[in] iMaxBackupIndex
* \param[in] pszPriority
* \return true: 初始化成功;false:初始化失败
* \author
* \date 2022-02-17
*/
bool SetConfigureFile(const char* pszConfigureFileName,
const char* pszInstanceName, const char* pszLogFileName,
int iMaxFileSize = 10485760, int iMaxBackupIndex = 10,
const char* pszPriority = "DEBUG");//设置日志配置文件
/*! \fn bool CLogRecord::InitLogInstance(const char* pszConfigureFileName, const char* pszInstanceName)
* \brief 初始化日志实例
* \param[in] pszConfigureFileName
* \param[in] pszInstanceName
* \return true: 初始化成功;false:初始化失败
* \author
* \date 2022-02-17
*/
bool InitLogInstance(const char* pszConfigureFileName,
const char* pszInstanceName);//初始化日志实例
//日志记录:DEBUG等级
void LogDebug(const char* pszStringLog, ...);
//日志记录:INFO等级
void LogInfo(const char* pszStringLog, ...);
//日志记录:WARN等级
void LogWarn(const char* pszStringLog, ...);
//日志记录:ERROR等级
void LogError(const char* pszStringLog, ...);
//日志记录:FATAL等级
void LogFatal(const char* pszStringLog, ...);
protected:
void* m_hCategory; //生成实例的句柄
};
#endif /* LOGMODULE_LOGRECORD_H */
CLogRecord.cpp
/*
* CLogOper.cpp
*
* Created on: 2022-02-16
* Author:
*/
#include "log4cpp/Category.hh"
#include "log4cpp/PropertyConfigurator.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/RollingFileAppender.hh"
#include "log4cpp/Priority.hh"
#include "CLogRecord.h"
#define LOG_OPER_MAX_SIZE 204800
CLogRecord::CLogRecord() {
// TODO Auto-generated constructor stub
m_hCategory = NULL;
}
CLogRecord::~CLogRecord() {
// TODO Auto-generated destructor stub
}
//获得日志的文件名
void CLogRecord::GetLogFileName(const char* pszLogFileDir,
const char* pszDeviceCode, int iFileNum, char* pszLogFileName) {
// TODO Auto-generated destructor stub
}
/*! \fn bool CLogRecord::SetConfigureFile(const char* pszConfigureFileName, const char* pszInstanceName, const char* pszLogFileName, int iMaxFileSize, int iMaxBackupIndex, const char* pszPriority)
* \brief 设置日志配置文件
* \param[in] pszConfigureFileName
* \param[in] pszInstanceName
* \param[in] pszLogFileName
* \param[in] iMaxFileSize
* \param[in] iMaxBackupIndex
* \param[in] pszPriority
* \return true: 初始化成功;false:初始化失败
* \author
* \date 2022-02-17
*/
bool CLogRecord::SetConfigureFile(const char* pszConfigureFileName, const char* pszInstanceName,
const char* pszLogFileName, int iMaxFileSize, int iMaxBackupIndex, const char* pszPriority)
{
if(m_hCategory)
{
delete (log4cpp::Category*)m_hCategory;
m_hCategory = NULL;
}
bool bCfgExists = true;
// 1 读取解析配置文件
// 读取出错, 完全可以忽略,可以定义一个缺省策略或者使用系统缺省策略
// BasicLayout输出所有优先级日志到ConsoleAppender
try {
log4cpp::PropertyConfigurator::configure(pszConfigureFileName);
} catch (log4cpp::ConfigureFailure& f) {
std::cout << "Configure Problem " << f.what() << std::endl;
bCfgExists = false;
}
bool bCreateNewCategory = false;
if (bCfgExists) {
m_hCategory = log4cpp::Category::exists(std::string(pszInstanceName));
if (m_hCategory == NULL) {
bCreateNewCategory = true;
}
} else {
bCreateNewCategory = true;
}
if (bCreateNewCategory) {
log4cpp::PatternLayout* pLayout1 = new log4cpp::PatternLayout();
pLayout1->setConversionPattern("$%5p %d{%Y-%m-%d %H:%M:%S.%l}@%m%n");
log4cpp::RollingFileAppender* rollfileAppender =
new log4cpp::RollingFileAppender("RollingFileAppender",
pszLogFileName, iMaxFileSize, iMaxBackupIndex);
rollfileAppender->setLayout(pLayout1);
m_hCategory = &(log4cpp::Category::getInstance(std::string(
pszInstanceName)));
((log4cpp::Category*) m_hCategory)->addAppender(rollfileAppender);
((log4cpp::Category*) m_hCategory)->setAdditivity(false);
try {
log4cpp::Priority::Value valPriority = log4cpp::Priority::getPriorityValue(pszPriority);
((log4cpp::Category*) m_hCategory)->setPriority(valPriority);
} catch (...) {
std::cout << "Unknown Priority \" " << pszPriority << "\""
<< std::endl;
}
}
//m_hCategory = log4cpp::Category::exists(std::string(pszInstanceName));
if (m_hCategory == NULL)
return false;
return true;
}
/*! \fn bool CLogRecord::InitLogInstance(const char* pszConfigureFileName, const char* pszInstanceName)
* \brief 初始化日志实例
* \param[in] pszConfigureFileName
* \param[in] pszInstanceName
* \return true: 初始化成功;false:初始化失败
* \author
* \date 2022-02-17
*/
bool CLogRecord::InitLogInstance(const char* pszConfigureFileName, const char* pszInstanceName)
{
if (m_hCategory == NULL)
{
// 1 读取解析配置文件
// 读取出错, 完全可以忽略,可以定义一个缺省策略或者使用系统缺省策略
// BasicLayout输出所有优先级日志到ConsoleAppender
try {
log4cpp::PropertyConfigurator::configure(pszConfigureFileName);
} catch (log4cpp::ConfigureFailure& f) {
//std::cout << "Configure Problem " << f.what() << std::endl;
return false;
}
m_hCategory = log4cpp::Category::exists(std::string(pszInstanceName));
if (m_hCategory == NULL)
return false;
}
return true;
}
void CLogRecord::LogDebug(const char* pszStringLog, ...) {
if (m_hCategory) {
char szTmpBuf[LOG_OPER_MAX_SIZE] = { 0 };
int offset = 0;
va_list va;
va_start(va,pszStringLog);
vsprintf(szTmpBuf + offset, pszStringLog, va);
va_end(va);
((log4cpp::Category*) m_hCategory)->debug(szTmpBuf);
}
}
void CLogRecord::LogInfo(const char* pszStringLog, ...) {
if (m_hCategory) {
char szTmpBuf[LOG_OPER_MAX_SIZE] = { 0 };
int offset = 0;
va_list va;
va_start(va,pszStringLog);
vsprintf(szTmpBuf + offset, pszStringLog, va);
va_end(va);
((log4cpp::Category*) m_hCategory)->info(szTmpBuf);
}
}
void CLogRecord::LogWarn(const char* pszStringLog, ...) {
if (m_hCategory) {
char szTmpBuf[LOG_OPER_MAX_SIZE] = { 0 };
int offset = 0;
va_list va;
va_start(va,pszStringLog);
vsprintf(szTmpBuf + offset, pszStringLog, va);
va_end(va);
((log4cpp::Category*) m_hCategory)->warn(szTmpBuf);
}
}
void CLogRecord::LogError(const char* pszStringLog, ...) {
if (m_hCategory) {
char szTmpBuf[LOG_OPER_MAX_SIZE] = { 0 };
int offset = 0;
va_list va;
va_start(va,pszStringLog);
vsprintf(szTmpBuf + offset, pszStringLog, va);
va_end(va);
((log4cpp::Category*) m_hCategory)->error(szTmpBuf);
}
}
void CLogRecord::LogFatal(const char* pszStringLog, ...) {
if (m_hCategory) {
char szTmpBuf[LOG_OPER_MAX_SIZE] = { 0 };
int offset = 0;
va_list va;
va_start(va,pszStringLog);
vsprintf(szTmpBuf + offset, pszStringLog, va);
va_end(va);
((log4cpp::Category*) m_hCategory)->fatal(szTmpBuf);
}
}
CLogRecord log_record;
CLogRecord log_record_timer_datatrans;
bool InitLog()
{
std::string log_config_file_name = "/usr/local/Projects/HDMap/HDMAP_database/software/lib/LogSetting_TrafficControlServer.ini"; //can ignore
std::string log_file_name = "/usr/local/Projects/HDMap/HDMAP_database/log/logTrafficControlServer.log";
std::string log_instance_name = "A1";
if(!log_record.InitLogInstance(log_config_file_name.c_str(), log_instance_name.c_str()))
{
printf("[%s][%s][%d]Log Init Failed", __FILE__, __FUNCTION__ ,__LINE__);
log_record.SetConfigureFile(log_config_file_name.c_str(), log_instance_name.c_str(), log_file_name.c_str(),10485780,5,"DEBUG");
}
log_record.LogDebug("[%s][%s][%d]This is the Log module use example1.", __CLASS__, __FUNCTION__ ,__LINE__);
log_config_file_name = "/usr/local/Projects/HDMap/HDMAP_database/software/lib/LogSetting_TrafficControlServer.ini"; //can ignore
log_file_name = "/usr/local/Projects/HDMap/HDMAP_database/log/logTrafficControlServer_TimerDataTrans.log";
log_instance_name = "A2";
if(!log_record_timer_datatrans.InitLogInstance(log_config_file_name.c_str(), log_instance_name.c_str()))
{
printf("[%s][%s][%d]Log Init Failed", __FILE__, __FUNCTION__ ,__LINE__);
log_record_timer_datatrans.SetConfigureFile(log_config_file_name.c_str(), log_instance_name.c_str(), log_file_name.c_str(),10485780,5,"DEBUG");
}
log_record_timer_datatrans.LogDebug("[%s][%s][%d]This is the Log module use example1.", __CLASS__, __FUNCTION__ ,__LINE__);
return true;
}