Monthly Archives: January 2017

Using log4cpp with Visual Studio 2015

First, let’s download log4cpp from sourceforge: http://log4cpp.sourceforge.net/

Log4cpp version is log4cpp-1.1.2rc5.

Let’s open log4cpp-1.1.2rc5log4cppmsvc10log4cpplog4cpp.vcxproj in VS2015. Try to build it. It fails. 2 errors…

snprintf & vsnprintf stuff. Ugly & cryptic error. Multiples definitions of body…

Let’s dive in the source code and we can see that a preprocessor declaration will help us.

Add HAVE_SNPRINTF to the project settings in preprocessor stuff. Build it. It is ok.

1> Creating library Debuglog4cpp.lib and object Debuglog4cpp.exp

1> log4cpp.vcxproj -> D:Devcpplog4cpp-1.1.2rc5log4cppmsvc10log4cppDebuglog4cpp.dll

========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Now, let’s build a sample client for using this dll.

We add a Win32 console project to the solution.

Add include folder to the client project:

Add the library folder to find the .lib file:

Add in your stdafx.h the following code:

#pragma once

#include "targetver.h"

#include <stdio.h>

#include <tchar.h>

#include <string>

#include <iostream>

using namespace std;

#include <log4cpp/RollingFileAppender.hh>

#include <log4cpp/Category.hh>

#include <log4cpp/Configurator.hh>

#include <log4cpp/Portability.hh>

#include <log4cpp/PropertyConfigurator.hh>

#pragma comment(lib, "log4cpp.lib")

The main program just put some data in file:

#include "stdafx.h"

#include "Logger.h"

int main()

{

MyLogger log;

if (!log.Init())

return 0;

log.LogDebug("Enter main...");

log.LogInfo("Main...");

log.LogDebug("Exit main");

return 0;

}

All the magic is contained in this code snipet:

#pragma once

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);

}

};

The configuration file is defined like:

#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=c:tempaLogger.log

log4cpp.appender.aLogger.maxFileSize=10240

log4cpp.appender.aLogger.maxBackupIndex=5

log4cpp.appender.aLogger.layout=PatternLayout

log4cpp.appender.aLogger.layout.ConversionPattern=[%d{%H:%M:%S,%l}] %m%n

#end of file