2.使用log4cpp记录日志

简介

log4cpp是个基于LGPL的开源项目,是基于优秀的日志处理跟踪项目Java语言的log4j移植过来的。

优点

  • 提供应用程序运行上下文,方便跟踪调试
  • 可扩展的、多种方式记录日志,包括命令行、文件、回卷文件、内存、syslog服务器、Win事件日志等
  • 可以动态控制日志记录级别,在效率和功能中进行调整
  • 所有配置可以通过配置文件进行动态调整
  • 多语言支持,包括Java(log4j),C++(log4cpp、log4cplus),C(log4c),python(log4p)等

配置及使用

  1. 包含头文件
#include 
#include 
#include 
#include 
  1. 初始化附加目的地(appenders)
// 输出到std::cout
log4cpp::Appender *appender = new log4cpp::OstreamAppender("root", &std::cout);
// 输出到log文件
log4cpp::Appender *appender = new log4cpp::FileAppender("root", "test.log");
  1. 设置输出格式(layout)
log4cpp::PatternLayout *patternLayout = new log4cpp::PatternLayout();
patternLayout->setConversionPattern("%d [%p] - %m%n");
appender->setLayout(patternLayout);

其他相关可以自己设置相关提示信息

  • %% - a single percent sign
  • %c - the category
  • %d - the date\n Date format: The date format character may be followed by a date format specifier enclosed between braces. For example, %d{%H:%M:%S,%l} or %d{%d %m %Y %H:%M:%S,%l}. If no date format specifier is given then the following format is used: "Wed Jan 02 02:03:55 1980". The date format specifier admits the same syntax as the ANSI C function strftime, with 1 addition. The addition is the specifier %l for milliseconds, padded with zeros to make 3 digits.
  • %m - the message
  • %n - the platform specific line separator
  • %p - the priority
  • %r - milliseconds since this layout was created.
  • %R - seconds since Jan 1, 1970
  • %u - clock ticks since process start
  • %x - the NDC
  • %t - thread name
  1. 设置类别(categories)和优先级(priority)
log4cpp::Category &root = log4cpp::Category::getRoot();
root.setPriority(log4cpp::Priority::NOTICE);
root.addAppender(appender);
  • 优先级:NOTSET < DEBUG < INFO < NOTICE < WARN < ERROR < CRIT < ALERT < FATAL = EMERG
  1. 定义一个宏定义
// 使用 LOG(WARN) << "message" 的格式来记录日志 
#define LOG(__level) log4cpp::Category::getRoot() << log4cpp::Priority::__level << "\n\t" << __FILE__ << " " << __LINE__ << ": "
  1. 在文件中记录打印日志
...
LOG(INFO) << "Device open success.";
...
LOG(ERROR) << "Device open failed.";
...

设置优先级以后只有高于所设置优先级的信息会被记录下来,因此可以通过宏定义来实现Debug和Release不同的信息优先级。

  1. 运行结果示例
2017-09-12 09:31:28,317 [INFO] - 
    /home/jiang/git/aero-node/an-core/example/qa_voice_capture.cc 36: Device open success.

2017-09-12 09:31:28,318 [INFO] - 
    /home/jiang/git/aero-node/an-core/example/qa_voice_capture.cc 59: Initialize hardware parameter success.

2017-09-12 09:31:28,318 [INFO] - 
    /home/jiang/git/aero-node/an-core/example/qa_voice_capture.cc 70: Set access type success.
  1. 其他
  • 可以将初始化配置自己封装到一个logger.h文件中,以后再需要使用直接include即可

你可能感兴趣的:(2.使用log4cpp记录日志)