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;
}
相关推荐
情深不寿3172 天前
C++特殊类的设计
开发语言·c++·单例模式
林开落L4 天前
线程进阶:线程池、单例模式与线程安全深度解析
linux·安全·单例模式·线程池
岁岁岁平安4 天前
Java的双重检查锁机制(DCL)与懒加载的单例模式
java·单例模式·synchronized·
为java加瓦7 天前
单例模式:原理、实现与演进
单例模式
磨十三7 天前
C++ 单例模式(Singleton)详解
c++·单例模式
默默coding的程序猿7 天前
1.单例模式有哪几种常见的实现方式?
java·开发语言·spring boot·spring·单例模式·设计模式·idea
程序员Aries10 天前
从零开始实现一个高并发内存池_DayThree:内存池整体框架与ThreadCache、TLS无锁访问
c++·学习·单例模式
爱奥尼欧10 天前
【Linux】系统部分——线程安全与线程的单例模式
linux·安全·单例模式
青草地溪水旁11 天前
第一章:单例模式 - 武林中的孤高剑客
单例模式
huangyuchi.11 天前
【Linux实战 】Linux 线程池的设计、实现与单例模式应用
linux·c++·单例模式·线程池·懒汉模式·项目·linux系统