本文主要是介绍log4cpp封装成独立的类(单例模式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、编译安装
二、封装使用
头文件Logger.h:
#ifndef DISTRIBUTED_LOGGER_H_
#define DISTRIBUTED_LOGGER_H_#include <string>
#include <log4cpp/Category.hh>class Logger{
public:bool init(const std::string& log_conf_file);static Logger* instance(){//返回单例——全局唯一对象return &instance_;}log4cpp::Category* get_handle(){return category_;}protected:static Logger instance_;log4cpp::Category* category_;
};#define LOG_INFO Logger::instance()->get_handle()->info
#define LOG_DEBUG Logger::instance()->get_handle()->debug
#define LOG_ERROR Logger::instance()->get_handle()->error
#define LOG_WARN Logger::instance()->get_handle()->warn#endif
实现类Logger.cpp:
#include "Logger.h"#include <iostream>
#include <log4cpp/Category.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PropertyConfigurator.hh>Logger Logger::instance_;bool Logger::init(const std::string& log_conf_file){try{log4cpp::PropertyConfigurator::configure(log_conf_file);}catch(log4cpp::ConfigureFailure& f){std::cerr << " load log config file " << log_conf_file.c_str() << " failed with result : " << f.what()<< std::endl;return false;}category_ = &log4cpp::Category::getRoot();return true;
}
这篇关于log4cpp封装成独立的类(单例模式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!