2015-11-17 41 views
3

在搜索什麼感覺太長時間後,我決定在stackoverflow上問這個簡單的問題: 如何爲log4cplus(1.1.2)創建自定義佈局? 最接近的相關問題是How do I add a custom filter in log4cplus?,作者將新類直接添加到log4cplus目錄中(或使用log4cplus命名空間?)。我沒有這個選項作爲log4plus頭文件和庫是獨立安裝(和簡單的設置命名空間log4cplus也不管用如何爲log4cplus創建自定義佈局

我想什麼是一個小例子,從log4cplus ::繼承的PatternLayout:

namespace myNameSpace { 
    class LOG4CPLUS_EXPORT MyPatternLayout: public ::log4cplus::PatternLayout { 
    public: 
     MyPatternLayout(const log4cplus::tstring& pattern); 
     MyPatternLayout(const log4cplus::helpers::Properties& properties); 
     ~MyPatternLayout(); 
    private: 
     // Disallow copying of instances of this class 
     MyPatternLayout(const MyPatternLayout&); 
     MyPatternLayout& operator=(const MyPatternLayout&); 
}; 
} 

我希望LOG4CPLUS_EXPORT需要註冊我的課的log4cplus框架,所以我可以在配置文件中使用的護理然而,增加

log4cplus.appender.STDOUT.layout=myNameSpace::MyPatternLayout 

導致錯誤:

log4cplus:ERROR Cannot find LayoutFactory: "myNameSpace::MyPatternLayout" 

那麼如何註冊一個自定義的Layout/Appender?

回答

0

在嘗試了很多事情之後,它歸結爲一個簡單的條目,必須在log4cplus::initialize();之後和log4cplus::PropertyConfigurator::doConfigure("<path to config file");之前放置。 如果要添加新的佈局在log4cplus命名空間,你可以簡單地

//example1 
log4cplus::initialize(); 
// register our stuff 
log4cplus::spi::LayoutFactoryRegistry& reg = log4cplus::spi::getLayoutFactoryRegistry(); 
LOG4CPLUS_REG_LAYOUT(reg, MyPatternLayout); 
log4cplus::PropertyConfigurator::doConfigure(Logger::mConfigFile); 

,或者,如果你想使用自己的名稱空間

//example2 
log4cplus::initialize(); 
// register our stuff 
log4cplus::spi::LayoutFactoryRegistry& reg = log4cplus::spi::getLayoutFactoryRegistry(); 
LOG4CPLUS_REG_PRODUCT (reg, "myNamespace::", MyPatternLayout, myNamespace::, log4cplus::spi::LayoutFactory); 
log4cplus::PropertyConfigurator::doConfigure(Logger::mConfigFile); 

然後,您可以在配置爲使用的佈局

log4cplus.appender.STDOUT.layout = log4cplus::MyPatternLayout #example 1 

log4cplus.appender.STDOUT.layout = myNamespace::MyPatternLayout #example 2 

夠簡單吧?我希望log4cplus有一個更接近.log4j的文檔

相關問題