I want to log to different files in my code.
How can i do that in Log4cxx with xml configuration or programatically in code...
- Suppose that I have 1.k,k+1,..n components.
- They run in the same application
- I want component k log to Logger-k, k+1 component log to Logger-k+1 at the same time
Update:
Logger.addAppender() approach:
log4cxx::helpers::Pool p;
std::string paramAppender = "appxNormalAppender";
std::string paramFileName = "\\Logs\\MyLog.txt";
LOG4CXX_DECODE_CHAR(logAppender, paramAppender );
LOG4CXX_DECODE_CHAR(logFileName, paramFileName );
FileAppenderPtr fileAppender =
logger->getLoggerRepository()->getRootLogger()->getAppender(logAppender);
if(fileAppender!= NULL)
{
fileAppender->setFile(logFileName);
fileAppender->activateOptions(p);
}
This does not work because
Suppose that i set FileName to Logger-k for k component, it logs to Logger-k, then i set file name to Logger-k+1 for compoent k+1, then both component k, and k+1 log the same loggerk+1 file. It seems last file name overrides or effects all others...
And
All compoenent compenent 1, ...compoeent k, componentk+1,.... component n are in the same application...
Create Each of the Loggers as normal, and then for each logger add a FileAppender set to the desired file via the Logger.addAppender() method.
This is another solution for dynamic logging using thread context in log4cxx with class
MDC
, after big frustration with current solutions. It basically allows to have aninstanceid
prefix added to theFile
property of aFileAppender
. It requires a customFileAppender
to be properly compiled and defined before loading of a configuration file. Works with usual old log4cxx 0.10.0 version. It can be used with the following snippet:Can be used with this property configuration file:
XFileAppender header:
XFileAppender source:
For dynamic components try this:
with simple trace.xml
You do need to create separate appenders for you loggers. In my example i've created afile1 and afile2 appenders. I have also created two loggers : my.logger1 and my.logger2. When you use my.logger1 it logs to mylog1 file, When you use my.logger2 it logs to mylog2 file.
Here is my log.properties file:
Here is an example programm:
example.cpp:
Here is Makefile( i suppose my log4cplus is built in parent dirrectory):
Try this example and you should understand how appenders works
Log4cplus is mostly like log4j. so you can read basic principles log4j. And To get classes names you got to visit log4cplus.sourceforge.net
About log format. Documentation for log4cplus is available only in doxygen . so here you can read about formating in pattern layout
And if you want to log process id , than you should use %i in your layout conversion pattern
example:
It will log process id and message