2012-03-10 59 views
2

如何使用log4cpp記錄多個字符串?如何一次性用log4cpp記錄多個變量?

E.g.如果我想記錄所有的argv的主:

#include <iostream> 
#include <log4cpp/Category.hh> 
#include <log4cpp/FileAppender.hh> 
#include <log4cpp/PatternLayout.hh> 

using namespace std; 

int main(int argc, char* argv[]) { 
    log4cpp::Appender *appender = new log4cpp::FileAppender("FileAppender","mylog"); 
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout(); 
    layout->setConversionPattern("%d: %p - %m %n"); 
    log4cpp::Category& category = log4cpp::Category::getInstance("Category"); 
    appender->setLayout(layout); 
    category.setAppender(appender); 
    category.setPriority(log4cpp::Priority::INFO); 

    category.info("program started"); // this works fine, I see it in the logfile 

    for(int i=0; i<argc; ++i) { 
     // next line does not compile: 
     category.info("argv["<<i<<"] = '"<<argv[i]<<"'"); 
    } 

    return 0; 
} 

category.info("argv["<<i<<"] = '"<<argv[i]<<"'"); 

不能編譯。很明顯,記錄器不能用作ostream。什麼是log4cpp方式記錄這樣的事情,最好立刻?

回答

5

你有兩個選擇:

  • 使用printf-style formatting

    for (int i = 0; i < argc; ++i) 
    { 
        category.info("argv[%d] = '%s'", i, argv[i]); 
    } 
    
  • 使用infoStream()

    for (int i = 0; i < argc; ++i) 
    { 
        category.infoStream() << "argv[" << i << "] = '" << argv[i] << "'"; 
    } 
    

我會去後者。

+0

即:預格式化一個字符串(使用printf或ostringstream)然後記錄該字符串? – 2012-03-10 11:01:44

+0

@JörgBeyer:無需預格式化。請看我更新的答案。 – Johnsyweb 2012-03-10 11:28:28

+1

酷,** category.infoStream()**是我想要的,但沒有找到。 – 2012-03-10 11:29:15

相關問題