Appenders, Loggers and Layout are the main components of the Apache log4cxx API which work together to expose a logging API to be used in C++ programs. (http://logging.apache.org/log4cxx/index.html)
To design a simple C++ application which logs to a file, you will have to: (http://logging.apache.org/log4cxx/apidocs/index.html)
1. Create a layout (SimpleLayout)
2. Create an appender (FileAppender) with the above layout
3. Create a logger and add the above appender
4. use the macros to log a message
#include <log4cxx/logstring.h>
#include <stdlib.h>
#include <log4cxx/logger.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/logger.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/simplelayout.h>
#include <iostream.h>
using namespace std;
using namespace log4cxx;
using namespace log4cxx::helpers;
int main() {
//setlocale(LC_ALL, "");
int result = EXIT_SUCCESS;
try {
// Create a basic configuration
// BasicConfigurator::configure();
// Create a SimpleLayout
log4cxx::LayoutPtr layout(new log4cxx::SimpleLayout());
// Create a new appender with the created layout
// Here we create a 'appender' to output to a FILE, instead of the 'console'.
// Here it outputs the logs to a file 'log.txt'
log4cxx::FileAppenderPtr appender(new log4cxx::FileAppender(layout, "log.txt", true));
// Create a new Logger with the name: 'MyLogger'
LoggerPtr mylogger = Logger::getLogger("MyLogger");
// Set Level for the new logger created
mylogger->setLevel(log4cxx::Level::getInfo());
// Add the appender to the 'logger' object created
mylogger->addAppender(appender);
// Logging request via macro
LOG4CXX_INFO(mylogger, "Trying out the Apache log4cxx API");
} catch (std::exception& ) {
result = EXIT_FAILURE;
}
return result;
}
Here is the 'log.txt' file contents:
INFO - Trying out the Apache log4cxx API


