log4cpp linux使用

来源:互联网 发布:js confirm的返回值 编辑:程序博客网 时间:2024/05/17 06:37

引用自:http://blog.163.com/modingfa_002/blog/static/11092546620105403456157/

log4cpp的安装和使用  

2010-06-04 00:34:56|  分类:log4 |字号 订阅

  • 以 root 用户安装 log4cpp,采用版本是
log4cpp-0.3.5rc3.tar.gz
  • 解包文件
cd /usr/localtar zxvf log4cpp-0.3.5rc3.tar.gz
  • 进入源码目录,并运行配置命令,增加 pthread 支持
cd log4cpp-0.3.5rc3./configure --with-pthreads
  • 配置完成后,需要修改2个地方(这是源码的 bug)
第一处:代码中多了一个分号
vi include/log4cpp/Manipulator.hh

删除29行最后的分号

第二处:打印线程号,线程id 是无符号长整型

vi src/PThreads.cpp
::sprintf(buffer, "%ld"pthread_self());
改为
::sprintf(buffer, "%lu"pthread_self());
  • 现在可以开始编译和安装

./configure

makemake install
  • 安装完成后,include 文件 和 lib 文件分别被安装到以下目录
/usr/local/include/usr/local/lib
  • 因此在编写代码时,可以这样包括 log4cpp 的头文件,例如
#include <log4cpp/Category.hh>
  • 最后是环境变量处理,需要在 LD_LIBRARY_PATH 中增加 log4cpp 库文件目录
vi /etc/profile.d/log4cpp.sh

内容为

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/libexport LD_LIBRARY_PATH

保存好文件后,增加文件的可执行权限

chmod a+x /etc/profile.d/log4cpp.sh
 
写代码测试
#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. 设置additivity为false,替换已有的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;}
编译:g++ -o testlog testlog -llog4cpp

原创粉丝点击