一、编译安装
二、封装使用
头文件Logger.h:
cpp
#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:
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;
}