Dec 11, 2011

log4cplus on Windows with MinGW

Today I tried the log4cplus Framework. Log4cplus is under the Apache License V2.0. 
This one should be more usefull for commercial projects. The last time I wrote about log4cpp.
This framework is under the LGPL licencse. I've found somewhere, that it should be possible to
use in commercial products, but with some restrictions, about only dynamically linked, hint where to
get the source, allowing the customer to change the lib, ....

I've not red the Apache License in detail, because for me it's just an attempt to use it for some testing
and learning a little C++.

log4cplus can be configured and built simple be an MinGW environment on Windows.

For running an app, the DLL of log4cplus must be found on the PATH.

A property file can look like:
log4cplus.rootCategory=ERROR, rootAppender
log4cplus.logger.Names=DEBUG, A1, A2

log4cplus.additivity.Names=false


log4cplus.appender.rootAppender=log4cplus::ConsoleAppender
log4cplus.appender.rootAppender.layout=log4cplus::PatternLayout
log4cplus.appender.rootAppender.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n

log4cplus.appender.A1=log4cplus::RollingFileAppender
log4cplus.appender.A1.File=A1.log
log4cplus.appender.A1.MaxFileSize=1MB
log4cplus.appender.A1.MaxBackupIndex=2
log4cplus.appender.A1.layout=log4cplus::SimpleLayout
log4cplus.appender.A1.layout.ContextPrinting=enabled
log4cplus.appender.A1.layout.DateFormat=ISO8601

log4cplus.appender.A2=log4cplus::ConsoleAppender
log4cplus.appender.A2.layout=log4cplus::PatternLayout
log4cplus.appender.A2.layout.ConversionPattern=[%d{%d %m %Y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n

The main module :

#include <log4cplus/configurator.h>
...
    std::string logFileName = "log4cplus.prop";
    log4cplus::PropertyConfigurator::doConfigure( logFileName );   
    cout << "Hello World" << endl;

Initializing the logger:

    Names::Names() :firstName(""), lastName(""), log(log4cplus::Logger::getInstance("Names"))
    {
        LOG4CPLUS_INFO( log, "Default Constructor" );
    }

Using in a complex format:

        LOG4CPLUS_INFO( log, "FirstName " <<
                     this->firstName
                                         << "; LastName "
                     << this->lastName );

Example of output:

[11 12 2011 15:50:41] [4624] INFO  Names %% - FirstName a; LastName b [Names.cpp:46]
[11 12 2011 15:50:41] [4624] INFO  Names %% - Combined name <a b> [Names.cpp:54]


Update: A follow up describes how to allow configuration changes of the logging for a running
process.