How do I log more than a single string with log4cpp?
E.g. if I want to log all argv's to 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;
}
the line
category.info("argv["<<i<<"] = '"<<argv[i]<<"'");
does not compile. Obviously the logger does not work as a ostream. What is the log4cpp way to log something like this, preferable at once?
You have two options:
for (int i = 0; i < argc; ++i)
{
category.info("argv[%d] = '%s'", i, argv[i]);
}
Use infoStream()
:
for (int i = 0; i < argc; ++i)
{
category.infoStream() << "argv[" << i << "] = '" << argv[i] << "'";
}
I'd go with the latter.