Dec 8, 2011

log4cpp Usage

The last time I compiled log4cpp on Windows with MinGW.

Now I got the following to work:
Names.hpp

#ifndef NAMES_HPP
#define    NAMES_HPP

#include <log4cpp/Category.hh>

namespace names {
  

    class Names
    {
    public:
        Names();
        Names(const Names& orig);
        virtual ~Names();
        void getNames();
        std::string myNames();
    private:
        std::string firstName;
        std::string lastName;
        log4cpp::Category& logger;
    };
}
#endif    /* NAMES_HPP */

using in Names.cpp as:
 


Names::Names(....) :logger(log4cpp::Category::getInstance("Names")
{
}

string Names::myNames()
    {
        std::stringstream combinedName;

        combinedName << this->firstName << " " << this->lastName;
        logger.info("Combined name <%s>", combinedName.str().c_str());
        return combinedName.str();
    }

and in the Main-Method:
int main(int argc, char** argv)
{
    std::string logFileName = "log4cpp.prop";
    try
    {
        log4cpp::PropertyConfigurator::configure(logFileName );
    }
    catch( log4cpp::ConfigureFailure e)
    {
        cerr << "Log4cpp Error: " << e.what() << endl;
    }

where the property configuration is:

log4j.rootCategory=DEBUG, rootAppender
log4j.category.Names=DEBUG, A2
log4j.additivity.Names=false
log4j.category.sub2=INFO
log4j.category.sub1.sub2=ERROR, A2

log4j.appender.rootAppender=org.apache.log4j.ConsoleAppender
log4j.appender.rootAppender.layout=org.apache.log4j.BasicLayout

log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.fileName=A1.log
log4j.appender.A1.layout=org.apache.log4j.BasicLayout

log4j.appender.A2=org.apache.log4j.ConsoleAppender
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%d{ISO8601}] [%c/%p] %m %n


and a sample output looks like:
[2011-12-08 14:55:00,182] [Names/INFO] Default Constructor
[2011-12-08 15:14:10,542] [Names/INFO] FirstName a; LastName b

For linking with MinGW, I had to add the following lib -lws2_32