log4cpp-【写日志】:使用log4cpp的基本步骤

                                     转自:http://wyw1986119.blog.163.com/blog/static/6332862008112793346967/

手动使用log4cpp的基本步骤如下:

1.       实例化一个layout 对象;

2.       初始化一个appender 对象;

3.       layout对象附着在appender对象上;

4.       调用log4cpp::Category::getInstance("name"). 实例化一个category对象;

5.       appender对象附到category上(根据additivity的值取代其他appender或者附加在其他appender后)。

6.       设置category的优先级;

// FileName: test_log4cpp1.cpp

// Test log4cpp by manual operation.

// Announce: use as your own risk.

// Compile : g++ -otest1 -llog4cpp test_log4cpp1.cpp

// Run     : ./test1

// Tested  : RedHat 7.2 log4cpp0.3.4b

// Author  : liqun (liqun@nsfocus.com)

// Data    : 2003-6-27

#include "log4cpp/Category.hh"

#include "log4cpp/FileAppender.hh"

#include "log4cpp/BasicLayout.hh"

int main(int argc, char* argv[])

{

        // 1实例化一个layout 对象

        log4cpp::Layout* layout =

        new log4cpp::BasicLayout();

        // 2. 初始化一个appender 对象

         log4cpp::Appender* appender = new

              log4cpp::FileAppender("FileAppender",

              "./test_log4cpp1.log");

         // 3. layout对象附着在appender对象上

         appender->setLayout(layout);

         // 4. 实例化一个category对象

         log4cpp::Category& warn_log =

        log4cpp::Category::getInstance("mywarn");

         // 5. 设置additivityfalse,替换已有的appender

        warn_log.setAdditivity(false);

         // 5. appender对象附到category

         warn_log.setAppender(appender);

         // 6. 设置category的优先级,低于此优先级的日志不被记录

         warn_log.setPriority(log4cpp::Priority::WARN);

         // 记录一些日志

         warn_log.info("Program info which cannot be wirten");

         warn_log.debug("This debug message will fail to write");

         warn_log.alert("Alert info");

         // 其他记录日志方式

         warn_log.log(log4cpp::Priority::WARN, "This will be a logged warning");

         log4cpp::Priority::PriorityLevel priority;

         bool this_is_critical = true;

         if(this_is_critical)

                 priority = log4cpp::Priority::CRIT;

         else

                 priority = log4cpp::Priority::DEBUG;

         warn_log.log(priority,"Importance depends on context");

        

         warn_log.critStream() << "This will show up << as "

         << 1 << " critical message"

         << log4cpp::CategoryStream::ENDLINE;

         // clean up and flush all appenders

         log4cpp::Category::shutdown();

         return 0;

}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值