Log4cplus使用

1.包含log4cplus头文件和lib
Log4cplus使用_第1张图片

2.封装LogHelper
LogHelper.h

#pragma once
#include "log4cplus/logger.h"

class LogHelper
{
public:
	LogHelper();
	~LogHelper();

public:
	int Load(const std::string& log_config_path, const std::string& logger_name);

	const log4cplus::Logger& GetLogger() const
	{
		return logger_;
	}

private:
	log4cplus::Logger logger_;
	static const unsigned watch_interval_ = 1*60*1000;
};

LogHelper.cpp

// LogHelper.cpp : 定义 DLL 应用程序的导出函数。
//
#include "LogHelper.h"
#include "log4cplus/configurator.h"
#include "log4cplus/loggingmacros.h"

LogHelper::LogHelper()
{
	log4cplus::initialize();
}

LogHelper::~LogHelper()
{
	log4cplus::Logger::shutdown();
}

int LogHelper::Load(const std::string& log_config_path, const std::string& logger_name)
{
	try
	{
		static log4cplus::ConfigureAndWatchThread config_thread(LOG4CPLUS_STRING_TO_TSTRING(log_config_path), watch_interval_);
		if (!log4cplus::Logger::exists(LOG4CPLUS_STRING_TO_TSTRING(logger_name)))
		{
			return -1;
		}
		logger_ = log4cplus::Logger::getInstance(LOG4CPLUS_STRING_TO_TSTRING(logger_name));
	}
	catch(...)
	{
		return -1;
	}

	return 0;
}

定义LogHelper使用方法

#pragma once

#include "LogHelper.h"
#include "log4cplus/loggingmacros.h"

extern LogHelper* g_log_helper;

#ifndef LOG_TRACE
#define LOG_TRACE(info_ostream) LOG4CPLUS_TRACE(g_log_helper->GetLogger(), info_ostream)
#endif

#ifndef LOG_DEBUG
#define LOG_DEBUG(info_ostream) LOG4CPLUS_DEBUG(g_log_helper->GetLogger(), info_ostream)
#endif

#ifndef LOG_INFO
#define LOG_INFO(info_ostream) LOG4CPLUS_INFO(g_log_helper->GetLogger(), info_ostream)
#endif

#ifndef LOG_WARN
#define LOG_WARN(info_ostream) LOG4CPLUS_WARN(g_log_helper->GetLogger(), info_ostream)
#endif

#ifndef LOG_ERROR
#define LOG_ERROR(info_ostream) LOG4CPLUS_ERROR(g_log_helper->GetLogger(), info_ostream)
#endif

#ifndef LOG_FATAL
#define LOG_FATAL(info_ostream) LOG4CPLUS_FATAL(g_log_helper->GetLogger(), info_ostream)
#endif

使用

	if (g_log_helper == NULL)
	{
		g_log_helper = new LogHelper();
	}
	int nret = g_log_helper->Load("./config/log.conf", "demo_app");
	LOG_INFO("CloudAppServer Is Already Runing...");

配置文件:

log4cplus.logger.demo_app=TRACE, demo_appender
log4cplus.additivity.demo_app=FALSE
log4cplus.appender.demo_appender=log4cplus::RollingFileAppender
log4cplus.appender.demo_appender.File=./demo_app.log
log4cplus.appender.demo_appender.MaxFileSize=20MB
log4cplus.appender.demo_appender.MaxBackupIndex=9
log4cplus.appender.demo_appender.layout=log4cplus::PatternLayout
log4cplus.appender.demo_appender.layout.ConversionPattern=[%-5p %c %t %D{%Y-%m-%d %H:%M:%S %Q} %b:%L] %m%n

你可能感兴趣的:(Log4cplus)