Main BLOGGER
Google
WWW THIS BLOG
Monday, September 26, 2005
 
A non-trivial log4cxx tutorial
Here we only discuss how to change the log4cxx properties on the fly.

1. Traverse current loggers list

LoggerList curLoggerList;
curLoggerList = Logger::getRootLogger()->getLoggerRepository()->getCurrentLoggers();
LoggerList::iterator i;
i = curLoggerList.begin();
while (i!=curLoggerList.end())
{
i->p->setLevel(log4cxx::Level::DEBUG); //i->p is the LoggerPtr
i++;
}
Logger::getRootLogger()->setLevel(log4cxx::Level::DEBUG);


2. create Layout, Appender and change conversion pattern on the fly

static const char patternOne[] = "%r [%t] %-5p %c- %m%n %x%n";
//create PatternLayout with pattern patternOne

PatternLayoutPtr myLayoutPtr;
ConsoleAppenderPtr myConsoleAppenderPtr;

ACE_NEW_RETURN(myLayoutPtr, PatternLayout, -1);
myLayoutPtr->setConversionPattern(patternOne);

//create ConsoleAppender with layout myLayoutPtr
ACE_NEW_RETURN(myConsoleAppenderPtr, ConsoleAppender, -1);
myConsoleAppenderPtr->setLayout(myLayoutPtr);


3. Create FileAppender on the fly

typedef log4cxx::helpers::ObjectPtrT
RollingFileAppenderPtr;

RollingFileAppenderPtr myRollingFileAppenderPtr;

LoggerPtr rootLogger = Logger::getRootLogger();

ACE_NEW_RETURN(myRollingFileAppenderPtr, RollingFileAppender, -1);

myRollingFileAppenderPtr->setFile("myLogFile_server.log");
myRollingFileAppenderPtr->setMaxBackupIndex( 10 );
myRollingFileAppenderPtr->setMaxFileSize( "10MB" );
myRollingFileAppenderPtr->setLayout(myFileLayoutPtr);
myRollingFileAppenderPtr->activateOptions();
rootLogger->addAppender( myRollingFileAppenderPtr );



4. Use NDC

char hostname [MAXHOSTNAMELEN+1];
ACE_OS::hostname (hostname, sizeof (hostname));
int port = 8888;

{ //since we need to clean the content in oss, we set it as local
log4cxx::StringBuffer oss;
oss << "[" << hostname << ":" << port << "]" <<
__FILE__ << ":" << __LINE__ << "\n";
log4cxx::NDC::push(oss.str());
}
LOG4CXX_DEBUG(rootLogger, _T("starting blocking connect"));
log4cxx::NDC::pop();



<< Home

Powered by Blogger

Google
WWW THIS BLOG