How to use log4cpp with Visual Studio 2012

Since end of december 2012, log4cpp has a support for VS 2010. You can now compile log4cpp without pain using VS 2010 or VS 2012.
Log4cpp is available on sourceforget.net at http://sourceforge.net/projects/log4cpp.
Log4cpp is small and efficient logging library with a support for configuration file with RollingFileAppender, etc.
First, you have to create a configuration file for describing your loggers wich are called appenders.

#file log4cpp.property

log4cpp.rootCategory=DEBUG, rootAppender
log4cpp.category.MyLogger=DEBUG, aLogger

log4cpp.appender.rootAppender=ConsoleAppender
log4cpp.appender.rootAppender.layout=BasicLayout

log4cpp.appender.aLogger=RollingFileAppender
log4cpp.appender.aLogger.fileName=aLogger.log
log4cpp.appender.aLogger.maxFileSize=10240
log4cpp.appender.aLogger.maxBackupIndex=5
log4cpp.appender.aLogger.layout=PatternLayout
log4cpp.appender.aLogger.layout.ConversionPattern=[%H:%M:%S.%l] %m%n

#end of file

Once your file is ready, you have to use the primitives of log4cpp to make traces available in the file name aLogger.log.


class MyLogger
{
public:
 MyLogger()
 {
 }
 virtual ~MyLogger()
 {
  log4cpp::Category::shutdown();
 }
 bool Init()
 {
  try
  {
   string initFileName = "log4cpp.property";
   log4cpp::PropertyConfigurator::configure(initFileName);
  }
  catch(log4cpp::ConfigureFailure& f)
  {
   std::cout << "Configure Problem" << f.what() << std::endl;
   return false;
  }
  return true;
 }
 void LogDebug(string message)
 {
  log4cpp::Category & mylogger = log4cpp::Category::getInstance("MyLogger");
  myLogger.debug(message);
 }
 void Loginfo(string message)
 {
  log4cpp::Category & mylogger = log4cpp::Category::getInstance("MyLogger");
  myLogger.info(message);
 }
};

With this helper class, you can manipulate your logging entries very easily.


int main()
{
 MyLogger log;
 if( !log.Init() )
  return 0;
 log.LogDebug("Enter main...");
 log.LogInfo("Main...");
 log.LogDebug("Exit main");
}
Advertisement

Tagged:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: