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;
}
相关推荐
游乐码11 小时前
Unity坦克案例疑难记录(一)
unity·单例模式
想学会c++3 天前
单例模式笔记总结
c++·笔记·单例模式
是个西兰花3 天前
单列模式和C++中的类型转换
c++·单例模式·设计模式·rtti
nnsix4 天前
设计模式 - 单例模式 笔记
笔记·单例模式·设计模式
cui_ruicheng4 天前
Linux线程(四):线程池、日志系统与单例模式
linux·开发语言·单例模式
2301_815279525 天前
实战分享实现 C++ 管理类单例模式:特点与最佳实践
javascript·c++·单例模式
阿维的博客日记5 天前
细说DCL单例模式和volatile有什么关系,volatile在DCL中是必要的吗??
单例模式·synchronized·happens-before
c++之路5 天前
单例模式(Singleton Pattern)
开发语言·c++·单例模式
青山师6 天前
CompletableFuture深度解析:异步编程范式与源码实现
java·单例模式·面试·性能优化·并发编程
这是程序猿8 天前
设计模式入门:Java 单例模式(Singleton)详解,从入门到实战
java·单例模式·设计模式