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;
}
相关推荐
“αβ”1 天前
线程安全的单例模式
linux·服务器·开发语言·c++·单例模式·操作系统·vim
蝸牛ちゃん1 天前
设计模式(六)创建型:单例模式详解
单例模式·设计模式·系统架构·软考高级
oioihoii4 天前
C++实战案例:从static成员到线程安全的单例模式
java·c++·单例模式
归云鹤4 天前
设计模式十:单件模式 (Singleton Pattern)
单例模式·设计模式
YxVoyager7 天前
C++设计模式:单例模式 (现代C++主流实现方式Meyer‘s Singleton + 使用CRTP模板化)
c++·单例模式·设计模式
不愧是你呀9 天前
Muduo库中单例模式详解
开发语言·c++·单例模式
数字芯片实验室9 天前
单例模式的智慧:从UVM看控制的艺术
单例模式
Dxy123931021610 天前
Python单例模式详解:从原理到实战的完整指南
javascript·python·单例模式
寒士obj10 天前
单例模式的设计与实现
java·单例模式
经典199211 天前
Java 设计模式及应用场景
java·单例模式·设计模式