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;
}
相关推荐
旧梦95273 天前
Java 单例模式:从基础到实战的完整指南
java·开发语言·单例模式
码匠许师傅3 天前
【设计模式精讲】4.单例模式(Singleton)
c++·单例模式·设计模式
米啦啦.5 天前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
布莱克6055 天前
单例模式详解:什么是单例模式,它能解决哪些问题?
开发语言·qt·单例模式
拓人间精准客5 天前
ToB 销售获客避坑指南:如何用全维度大数据实现降本增效
大数据·数据结构·单例模式
Java后端的Ai之路7 天前
05、Python单例模式完全指南
开发语言·人工智能·python·单例模式·oracle
小此方9 天前
Linux加餐(二):藏在Linux中的设计模式(二)单例模式与线程池
linux·单例模式·设计模式
iFlyCai13 天前
iOS中的单例模式详解
ios·单例模式·objective-c·多线程·swift
captain37615 天前
多线程单例模式
java·单例模式·java-ee
2301_7779983419 天前
C++ 单例模式详解:饿汉、懒汉,以及“对象”和“对象指针”到底有什么区别
开发语言·c++·单例模式