跳转至

配置文件

log4cpp支持从一个配置文件中读取Category、Appender和Layout的优先级和相互附属关系。

示例

  1. log4cpp.conf

    #log4cpp配置文件
    #定义Root category的属性
    log4cpp.rootCategory=DEBUG, RootLog
    
    #定义RootLog属性
    log4cpp.appender.RootLog=ConsoleAppender
    log4cpp.appender.RootLog.layout=PatternLayout
    log4cpp.appender.RootLog.layout.ConversionPattern=%d [%p] -%m%n
    
    #定义sample category的属性
    log4cpp.category.sample=DEBUG, sample
    
    #定义sample属性
    log4cpp.appender.sample=FileAppender
    log4cpp.appender.sample.fileName=sample.log
    log4cpp.appender.sample.layout=PatternLayout
    log4cpp.appender.sample.layout.ConversionPattern=%d [%p] -%m%n
    
    #定义sample.soncategory的属性
    log4cpp.category.sample.son=DEBUG, son
    
    #定义son的属性
    log4cpp.appender.son=FileAppender
    log4cpp.appender.son.fileName=son.log
    log4cpp.appender.son.layout=PatternLayout
    log4cpp.appender.son.layout.ConversionPattern=%d[%p] - %m%n
    
    #定义sample.daughtercategory的属性
    log4cpp.category.sample.daughter=DEBUG,daughter
    
    #定义daughter属性
    log4cpp.appender.daughter=FileAppender
    log4cpp.appender.daughter.fileName=daughter.log
    log4cpp.appender.daughter.layout=PatternLayout
    log4cpp.appender.daughter.layout.ConversionPattern=%d [%p]- %m%n
    

  2. log4cpp_test.cpp

    #include<iostream>
    #include<log4cpp/Category.hh>
    #include<log4cpp/PropertyConfigurator.hh>
    
    int main(int argc,char* argv[])
    {
        try
        {
            log4cpp::PropertyConfigurator::configure("./log4cpp.conf");
        }
        catch(log4cpp::ConfigureFailure& f)
        {
            std::cout<< "Configure Problem "<< f.what()<< std::endl;
            return -1;
        }
    
        log4cpp::Category& root =log4cpp::Category::getRoot();
        log4cpp::Category& sub1 =log4cpp::Category::getInstance(std::string("sub1"));
        log4cpp::Category& sub3 =log4cpp::Category::getInstance(std::string("sub1.sub2"));
        sub1.info("This is someinfo");
        sub1.alert("Awarning");
        // sub3 only have A2 appender.
        sub3.debug("This debug messagewill fail to write");
        sub3.alert("All hands abandonship");
        sub3.critStream() <<"This will show up<< as "<< 1 <<" critical message"<<log4cpp::CategoryStream::ENDLINE;
        sub3<<log4cpp::Priority::ERROR<<"And this will be anerror"  <<log4cpp::CategoryStream::ENDLINE;
        sub3.log(log4cpp::Priority::WARN, "This will be a logged warning");
        return0;
    }
    

【配置文件使用总结】

  1. category 是"log4cpp.category." + "categoryname"
  2. category 名字可以用"."分隔,以标识包含关系
  3. appender 是"log4cpp.appender." + "appendername"
  4. appender 名字 不能用 "." 分隔,即是说 appender 是没有包含关系的