log4cpp 配置 与 使用

摘要:
这个优先级的含义是:配置文件中设置了级别是debug,则任意的log都能打出来;如果配置了级别是fatal,则只有高于他优先级的日志才可以打印出来additivity限制appender会不会被继承2.程序举例#include#include#include#include#defineLOGFILE"./test.log"intmain(){/*SettingupAppender,layoutandCategory*/log4cpp::Appender*appender=newlog4cpp::FileAppender;//第一个参数是appender的名字,第二个是log文件的名字log4cpp::Layout*layout=newlog4cpp::SimpleLayout();//log4cpp::Layout*layout=newlog4cpp::BasicLayout();log4cpp::Category&category=log4cpp::Category::getInstance;appender-˃setLayout;category.setAppender;category.setPriority;/*Theactuallogging*/category.info;category.notice;category.warn;}以上程序将得到下面的log输出:INFO:ThisisfortracingtheflowNOTICE:ThisistonotifycertaineventsWARN:Thisistogeneratecertainwarnings这个程序里面可以把log4cpp::Layout*layout=newlog4cpp::BasicLayout();的注释取消,注释掉上面的语句。
1. 基本概念
  • categories 日志的层级体系
  • appenders 日志打印到什么地方,可以是文件,也可以是终端
  • layouts 日志输出格式,定义类似于printf中的输出方式。有三种,后面都有例子,这三种分别是:basic,simple,pattern
  • priority 日志的级别,所有的级别有:EMERG、FATAL、ALERT、CRIT、ERROR、WARN、NOTICE、INFO、DEBUG、NOTSET,其中NOTSET < DEBUG < INFO < NOTICE < WARN < ERROR < CRIT < ALERT < FATAL = EMERG。这个优先级的含义是:配置文件中设置了级别是debug,则任意的log都能打出来;如果配置了级别是fatal,则只有高于他优先级的日志才可以打印出来
  • additivity 限制appender会不会被继承(后面还有补充说明)

2. 程序举例

#include<stdio.h>
#include
<log4cpp/Category.hh>
#include
<log4cpp/FileAppender.hh>
#include
<log4cpp/SimpleLayout.hh>#defineLOGFILE"./test.log"intmain(){
/*SettingupAppender,layoutandCategory*/
log4cpp::Appender
*appender=newlog4cpp::FileAppender("FileAppender",LOGFILE);//第一个参数是appender的名字,第二个是log文件的名字
log4cpp::Layout
*layout=newlog4cpp::SimpleLayout();
//log4cpp::Layout*layout=newlog4cpp::BasicLayout();log4cpp::Category&category=log4cpp::Category::getInstance("abc");
appender
->setLayout(layout);
category.setAppender(appender);
category.setPriority(log4cpp::Priority::INFO);
/*Theactuallogging*/
category.info(
"Thisisfortracingtheflow");
category.notice(
"Thisistonotifycertainevents");
category.warn(
"Thisistogeneratecertainwarnings");

}

以上程序将得到下面的log输出:

INFO : This is for tracing the flow
NOTICE : This is to notify certain events

WARN : This is to generate certain warnings

这个程序里面可以把log4cpp::Layout*layout=newlog4cpp::BasicLayout();的注释取消,注释掉上面的语句。将得到下面的log输出:

1308806376 INFO abc : This is for tracing the flow
1308806376 NOTICE abc : This is to notify certain events

1308806376 WARN abc : This is to generate certain warnings

两者的区别就在于使用了不同的layout,一个是simple一个是basic的。

要做到复杂格式的输出就要使用第三种,即:PatternLayout,下面借助配置文件来说明这种方式的使用:

3. 配置文件说明

配置文件log4cpp.conf:

#定义了3个categorysub1,sub2,sub3
#其中sub2和sub3设置了additivity属性为false;sub1的additivity属性默认为true
rootCategory
=DEBUG,rootAppender
category.sub1
=,A1
category.sub2
=INFO,A2
additivity.sub2
=false
category.sub3
=ERROR,A3
additivity.sub3
=false
#定义rootAppender类型和layout属性,这里使用了
BasicLayout
appender.rootAppender
=org.apache.log4cpp.ConsoleAppender
appender.rootAppender.layout
=org.apache.log4cpp.
BasicLayout

#定义A1的属性,
这里使用了SimpleLayout
appender.A1
=org.apache.log4cpp.FileAppender
appender.A1.fileName
=./log/A1.log
appender.A1.layout
=org.apache.log4cpp.SimpleLayout
#定义A2的属性,这里使用了
PatternLayout
appender.A2
=org.apache.log4cpp.ConsoleAppender
appender.A2.layout
=org.apache.log4cpp.PatternLayout
appender.A2.layout.ConversionPattern
=Themessage'%m'attime%d%n
#定义A3的属性
appender.A3
=org.apache.log4cpp.RollingFileAppender
appender.A3.fileName
=./log/A3.log
appender.A3.maxFileSize
=50
appender.A3.maxBackupIndex
=3
appender.A3.backupPattern
=%Y-%m-%d
appender.A3.layout
=org.apache.log4cpp.PatternLayout
appender.A3.layout.ConversionPattern
=%d{%Y-%m-%d%H:%M:%S}[%p]:[%c]%m%n

4. 带配置文件的程序举例

源代码:

#include"log4cpp/Category.hh"
#include
"log4cpp/PropertyConfigurator.hh"intmain(intargc,char*argv[]){
//1读取解析配置文件
//读取出错,完全可以忽略,可以定义一个缺省策略或者使用系统缺省策略
//BasicLayout输出所有优先级日志到ConsoleAppendertry
{
log4cpp::PropertyConfigurator::configure(
"./log4cpp.conf");
}
catch(log4cpp::ConfigureFailure&f)
{
std::cout
<<"ConfigureProblem"<<f.what()<<std::endl;
return-1;
}
//2实例化category对象
//这些对象即使配置文件没有定义也可以使用,不过其属性继承其父category
//通常使用引用可能不太方便,可以使用指针,以后做指针使用log4cpp::Category&root=log4cpp::Category::getRoot();
log4cpp::Category
&sub1=log4cpp::Category::getInstance(std::string("sub1"));
log4cpp::Category
&sub2=log4cpp::Category::getInstance(std::string("sub2"));
log4cpp::Category
&sub3=log4cpp::Category::getInstance(std::string("sub3"));
log4cpp::Category
&sub4=log4cpp::Category::getInstance(std::string("sub4"));
//正常使用这些category对象进行日志处理。root.fatal("root'slog");
//sub1hasappenderA1androotappender.sincetheadditivitypropertyissettruebydefaultsub1.info("sub1'slog");
//sub2hasappenderA2appender.sincetheadditivitypropertyissettofalsesub2.alert("sub2'slog");
//sub3onlyhasA3appender.sincetheadditivitypropertyissettofalsesub3.debug("sub3'slog");
sub3.alert(
"sub3'slog");
//sub4cannotbefoundintheconfigfile,sotherootcategory'sappenderandlayoutareusedsub4.warn("sub4'slog");
return0;
}

终端打印出来的log:

1308828470 FATAL : root's log
1308828470 INFO sub1 : sub1's log
The message 'sub2's log' at time 2011-06-23 19:27:50,624

1308829427 WARN sub4 : sub4's log

log/A1.log的内容:

INFO : sub1's log

log/A3.log的内容:

2011-06-23 19:27:50 [ALERT]: [sub3] sub3's log

5. 配置参考

Appender Additivity
The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity".
However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P.

Loggers have their additivity flag set to true by default.

参考来自:http://logging.apache.org/log4j/1.2/manual.html

Sets the format of log lines handled by thisPatternLayout.

By default, set to "%m%n".
Format characters are as follows:

  • %%%%- a single percent sign
  • %c- the category
  • %d- the date
    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- theNDC
  • 参考来自:http://log4cpp.sourceforge.net/api/classlog4cpp_1_1PatternLayout.html

    这也是一篇不错的参考文章:

    http://joysofprogramming.com/log4cpp-tutorial/

    免责声明:文章转载自《log4cpp 配置 与 使用》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

    上篇【IDEA】IDEA中maven项目pom.xml依赖不生效解决JasperReports入门教程(二):中文打印下篇

    宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

    相关文章

    Oracle获取alter.log的方法

    10g下:可以在 admin{sid}pfile文件下的init.ora文件中找到以下内容:audit_file_dest = C:ORACLEPRODUCT10.2.0ADMINORCLADUMP background_dump_dest = C:ORACLEPRODUCT10.2.0ADMINORCLBDUMP user_dump_dest = C:O...

    C# 读取二进制文件

    using UnityEngine; using System.Collections; using System; using System.IO; public class Test : MonoBehaviour { void Start () { TextAsset binData=Resources...

    Postgresql的日志配置

    背景   公司的项目中使用了postgresql(简称pg)作为其数据库管理系统,前两天环境突然崩溃了,页面无法打开。经过排查,我发现是数据库所在机器磁盘满了,通过目录和文件排序,原来是pg的日志太多(大约保留了大半年的日志在磁盘上没有被清理)。   我看了下pg的日志配置,发现基本都是用的默认配置,日志滚动没有开启,于是乎做了下相关配置优化后对pg进行重...

    isequal 和startswith 使用

    如果要把不同服务器发送过来的日志保存到不同的文件, 可以这样操作: :fromhost-ip, isequal, “192.168.0.160″ /var/log/host160.log :FROMHOST-IP, isequal, “192.168.0.161″ /var/log/host161.log :FROMHOST-IP, startswith,...

    抓取Android应用的log

    今天测试软件时,遇到一个bug,因为开发说那边不复现,所以为了更好追踪这个问题,需要抓取复现步骤地log. 在网上查了相关资料,同时结合自己遇到的问题,总结如下。 1. 抓取Android 应用log的方法 2. adb server is out of date.killing的解决办法 3. 在Eclipse中怎样成功连接Android手机 1. 抓取...

    fio 2种画图方法 fio_generate_plots 和 gfio

    fio 安装fio apt-get install fio 可以把fio的输出数据自动画图的插件gnuplot apt-get install gnuplot 1.输出bw,lat和iops数据并画图 fio安装完后自带有一个高级脚本fio_generate_plots能够根据fio输出的数据进行画图。操作流程如下: 1.1设置fio输出详细日志 f...