2012-12-20 149 views
1

我以正常的方式使用log4cxx,它爲log4cxx提供了一個屬性文件。在這裏,我們可以找到一個參考:如何設置沒有屬性文件的log4cxx屬性?

log4cxx: configuring appender with arguments

Reading Property Info in Log4cxx

但是,如果我想設置log4cxx在沒有財產的文件我的C++代碼,我該怎麼辦?我檢查log4cxx代碼,並試圖通過log4cxx ::幫手::屬性設置屬性,這裏是我的示例代碼:

log4cxx::helpers::Properties properties; 
    properties.setProperty(L"log4j.rootLogger",L"DEBUG"); 
    properties.setProperty(L"log4j.appender",L"ca"); 
    properties.setProperty(L"log4j.appender",L"fa"); 

    properties.setProperty(L"log4j.appender.fa",L"org.apache.log4j.FileAppender"); 
    properties.setProperty(L"log4j.appender.fa.Append",L"false"); 
    properties.setProperty(L"log4j.appender.fa.File",L"./test.log"); 
    properties.setProperty(L"log4j.appender.fa.layout",L"org.apache.log4j.PatternLayout"); 
    properties.setProperty(L"log4j.appender.fa.layout.ConversionPattern",L"%d [%t] %-5p %.16c - %m%n"); 

    properties.setProperty(L"log4j.appender.ca",L"org.apache.log4j.ConsoleAppender"); 
    properties.setProperty(L"log4j.appender.ca.layout",L"log4j.appender.ca.layout"); 
    properties.setProperty(L"log4j.appender.ca.layout.ConversionPattern",L"%d [%t] %-5p %.16c - %m%n"); 

    log4cxx::PropertyConfigurator::configure(properties); 

但我的示例代碼不起作用。爲什麼?任何人都知道如何初始化沒有屬性文件的log4cxx記錄器?

感謝

水林

回答

2

我找到的代碼示例中的log4cxx wiki有益面臨着同樣的挑戰時。

2

我寫了一篇關於這一點:

http://bigbang.waterlin.org/bang/the-way-to-set-log4cxx-properties-without-using-property-file/

添加更多的參考。

如果你想重定向日誌在同一時間提交&控制檯,請使用如下代碼:

#include <log4cxx/logger.h> 
#include <log4cxx/helpers/pool.h> 
#include <log4cxx/basicconfigurator.h> 
#include <log4cxx/fileappender.h> 
#include <log4cxx/simplelayout.h> 
#include "log4cxx/consoleappender.h" 

LoggerPtr logger; 

int main() { 
    log4cxx::FileAppender * fileAppender = new log4cxx::FileAppender(log4cxx::LayoutPtr(new log4cxx::SimpleLayout()), L"logfile", false); 

    log4cxx::ConsoleAppender * consoleAppender = new log4cxx::ConsoleAppender(log4cxx::LayoutPtr(new log4cxx::SimpleLayout())); 

    log4cxx::helpers::Pool p; 
    fileAppender->activateOptions(p); 

    log4cxx::BasicConfigurator::configure(log4cxx::AppenderPtr(fileAppender)); 
    log4cxx::BasicConfigurator::configure(log4cxx::AppenderPtr(consoleAppender)); 
    log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getDebug()); 
    log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("logger"); 

    LOG4CXX_INFO(logger,"Created FileAppender appender"); 

    return 0; 
} 
0

您可以使用ByteArrayInputStream進行建立log4cxx

std::vector<byte> vc; 
// copy property file content into vc 
log4cxx::helpers::ByteArrayInputStreamPtr bais(
    new log4cxx::helpers::ByteArrayInputStream(vc)); 
log4cxx::helpers::Properties pp; 
pp.load(bais); 
log4cxx::PropertyConfigurator::configure(pp); 
+0

歡迎SO。你應該添加關於你放在這裏的代碼的解釋。 – nakib