log4cpp封装成独立的类(单例模式)

一、编译安装

二、封装使用

头文件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;
}
相关推荐
Wadli10 小时前
C++语法 | static静态|单例模式
开发语言·c++·单例模式
.豆鲨包12 小时前
【设计模式】单例模式
java·单例模式·设计模式
Ronin3052 天前
【Linux系统】单例式线程池
linux·服务器·单例模式·线程池·线程安全·死锁
青草地溪水旁2 天前
设计模式(C++)详解—单例模式(2)
c++·单例模式
白玉cfc3 天前
【OC】单例模式
开发语言·ios·单例模式·objective-c
T1an-13 天前
C++版单例模式-现代化简洁写法
c++·单例模式
青草地溪水旁4 天前
设计模式(C++)详解—单例模式(1)
c++·单例模式
库奇噜啦呼4 天前
【iOS】单例模式
ios·单例模式
馨谙4 天前
设计模式之单例模式大全---java实现
java·单例模式·设计模式
土了个豆子的4 天前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#