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;
}
相关推荐
今天会营业18 天前
单例模式:饿汉和懒汉
单例模式
小小晓.19 天前
C++单例模式万字详解:6种实现演进+线程安全彻底解决+CRTP终极模板
c++·单例模式
软件黑马王子20 天前
3.单例模式问题1:构造函数
开发语言·单例模式·c#
软件黑马王子20 天前
4.单例模式问题2:重复挂载
开发语言·单例模式·c#
软件黑马王子20 天前
5.单例模式问题3:多线程问题
单例模式·前端框架·c#
旧梦952724 天前
Java 单例模式:从基础到实战的完整指南
java·开发语言·单例模式
码匠许师傅24 天前
【设计模式精讲】4.单例模式(Singleton)
c++·单例模式·设计模式
米啦啦.1 个月前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
布莱克6051 个月前
单例模式详解:什么是单例模式,它能解决哪些问题?
开发语言·qt·单例模式
拓人间精准客1 个月前
ToB 销售获客避坑指南:如何用全维度大数据实现降本增效
大数据·数据结构·单例模式