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;
}
相关推荐
会编程的李较瘦6 分钟前
【期末考试总结】spark课程知识点
大数据·单例模式·spark
java porter2 天前
系统架构设计之单例模式(下)
开发语言·javascript·单例模式
java porter3 天前
系统架构设计之单例模式(上)
单例模式
萧曵 丶3 天前
Java 安全的单例模式详解
java·开发语言·单例模式
期待のcode4 天前
Java的单例模式
java·开发语言·单例模式
xxxxxxllllllshi4 天前
深入解析单例模式:从原理到实战,掌握Java面试高频考点
java·开发语言·单例模式·面试
ShineSpark4 天前
C++单例模式的演进:从经典实现到现代线程安全范式
c++·安全·单例模式
爱编码的傅同学5 天前
【单例模式】深入理解懒汉与饿汉模式
java·javascript·单例模式
Geoking.7 天前
【设计模式】理解单例模式:从原理到最佳实践
单例模式·设计模式
一颗青果8 天前
单例模式 | 死锁
linux·服务器·单例模式·1024程序员节