Apache log4cxx framework – Example using Pthreads – Part Two
SathishOctober 11, 2010
This blog post is continued from Apache log4cxx framework – Part One.
This post comprises of a simple Configuration file and how it can be incorporated to a c++ code file for using the log4cxx framework.
Configuration File (log4cxx.properties)
properties
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
C++ Code Example with Pthreads
cpp
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <pthread.h>
using namespace log4cxx;
LoggerPtr logger(Logger::getLogger("MyApp"));
void* threadFunction(void* arg) {
int threadId = *((int*)arg);
LOG4CXX_INFO(logger, "Thread " << threadId << " started");
// Do some work
LOG4CXX_DEBUG(logger, "Thread " << threadId << " processing");
LOG4CXX_INFO(logger, "Thread " << threadId << " finished");
return NULL;
}
int main(int argc, char* argv[]) {
PropertyConfigurator::configure("log4cxx.properties");
pthread_t threads[5];
int threadIds[5];
for (int i = 0; i < 5; i++) {
threadIds[i] = i;
pthread_create(&threads[i], NULL, threadFunction, &threadIds[i]);
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
The log4cxx framework is thread-safe, making it ideal for multi-threaded applications using pthreads.