• Linux C++,使用log4cpp记录日志示例详解


    Linux C++,使用log4cpp记录日志示例详解

    log4cpp 是比较普遍使用的开源日志记录模块。目前有各种平台下的版本,可用于JAVA、C++、C#等各种开发语言。。本文重点详细说明在Linux 下C++开发示例。

    • 1、ini配置文件格式说明
    • 2、封装log4cpp日志接口CLogRecord(.h、.cpp)
    • 3、C++调用代码

    1、ini配置文件格式说明

    示例中,举例了同时对两个日志对象进行了说明。注意其中的: appender1、appender2,A1、A2的定义之处。

    • fileName: 设置生成的日志文件名称及路径
    • maxFileSize:设置单个日志文件大小
    • maxBackupIndex:设置日志文件备份个数,超过个数,自动循环记录
    [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
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2、封装log4cpp日志接口CLogRecord

    2.1 CLogRecord.h

    /*
     * 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 */
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    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);
    	}
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204

    3、C++调用代码

    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;
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
  • 相关阅读:
    有了这45个小技巧,再也不怕女朋友代码写得烂了!!
    什么是GPT-4
    Java 中常用的进制转换
    9.20金融科技(比特币)
    IoTBrowser V2.0:引领物联网时代的全新浏览器
    第3章C/C++流程控制
    postgresql-自增字段
    【计算机视觉 | 目标检测】arxiv 计算机视觉关于目标检测的学术速递(8 月 31 日论文合集)
    ZLMediaKit安装配置和推拉流
    CTFshow 信息收集 web12 13 14 15
  • 原文地址:https://blog.csdn.net/limeigui/article/details/125458542