(原创)一个log4cpp帮助类

引用log4cpp头文件和lib文件后,通过一个帮助类来输出日志,帮助类中定义了一些静态方法,实现日志的输出,使用起来很简单。代码如下:

#include <log4cpp/Category.hh>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/OstreamAppender.hh>
using namespace log4cpp;

#include <boost/utility.hpp>
#include <boost/thread.hpp>

boost::once_flag g_call_once=BOOST_ONCE_INIT;
class Logger : boost::noncopyable
{
private:
    Logger(void){}    

    static void Init()
    {
    #if _DEBUG
        OstreamAppender* fileAppender=new OstreamAppender("osAppender",&cout);
    #else
        RollingFileAppender* fileAppender=new RollingFileAppender("fileAppender","..\\log\\antbus.log");
    #endif

        PatternLayout* pLayout=new PatternLayout();
        pLayout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S,%l}: %p %c %x: %m%n");
        fileAppender->setLayout(pLayout);

        Category& root= Category::getRoot();
        root.addAppender(fileAppender);
        root.setPriority(Priority::INFO);
    }
public:
    ~Logger(void){}

    void static Debug(string str)
    {
        boost::call_once(g_call_once, Init);
        Category::getRoot().debug(str);
    }

    void static Info(string str)
    {
        boost::call_once(g_call_once, Init);
        Category::getRoot().info(str);
    }

    void static Warn(string str)
    {
        boost::call_once(g_call_once, Init);
        Category::getRoot().warn(str);
    }

    void static Error(string str)
    {
        boost::call_once(g_call_once, Init);
        Category::getRoot().error(str);
    }

    void static Faltal(string str)
    {
        boost::call_once(g_call_once, Init);
        Category::getRoot().fatal(str);
    }
};

测试代码:

    Logger::Error("erro1");
    Logger::Info("info");
    Logger::Warn("warn");
    Logger::Faltal("faltal");

测试结果:

posted on 2013-04-15 14:03  qicosmos(江南)  阅读(1469)  评论(1编辑  收藏  举报

导航