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;
}
相关推荐
她说彩礼65万几秒前
C#设计模式 单例模式实现方式
单例模式·设计模式·c#
nice_lcj5207 小时前
认识多线程:单例模式
java·开发语言·单例模式
Adellle19 小时前
2.单例模式
java·开发语言·单例模式
乙己4072 天前
设计模式——单例模式(singleton)
java·c++·单例模式·设计模式
空空kkk3 天前
单例模式详解
单例模式
shaominjin1234 天前
单例模式:设计模式中的“独一无二“之道
android·单例模式·设计模式
北邮-吴怀玉6 天前
6.3.3.1 大数据方法论与实践指南-大数据质量度量指标体系
大数据·单例模式
报错小能手7 天前
C++笔记(面向对象)详解单例模式
c++·笔记·单例模式
闲人编程10 天前
Python设计模式实战:用Pythonic的方式实现单例、工厂模式
开发语言·python·单例模式·设计模式·工厂模式·codecapsule·pythonic
W.Buffer11 天前
设计模式-单例模式:从原理到实战的三种经典实现
开发语言·javascript·单例模式