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 ([email protected])

// 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;

}

你可能感兴趣的:(log4cpp-【写日志】:使用log4cpp的基本步骤)