3

如何使用 log4cpp 记录多个字符串?

例如,如果我想将所有 argv 记录到 main:

#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 方式来记录这样的事情,最好是一次?

4

1 回答 1

7

你有两个选择:

  • 使用printf-style 格式

    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] << "'";
    }  
    

我会选择后者。

于 2012-03-10T10:59:47.163 回答