I am using log4cxx in a normal way, which provides a property file for log4cxx. Here we can find some references1, 2 about it.

But if I want to set log4cxx properties in my C++ code without using property file, what should I do? Here is the code example from log4xxx Wiki:

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

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

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

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

LOG4CXX\_INFO(logger,"Created FileAppender appender");

return 0;

}

The above code is only used for recording logs into log file. If we want to direct logs to console as well as writing to file, we need to add log4cxx::ConsoleAppender class into log4cxx::BasicConfigurator. Here is the sample code:

#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;

}

By the above code, the log will be redirected to file and console at the same time without a config file.

Footnotes:

1 log4cxx: configuring appender with arguments

2 Reading Property Info in Log4cxx