Question

Is it possible to programmatically configure log4cpp?

I want to configure it as it would be configured by supplying the following config file.

appender root basic console
priority root DEBUG
Was it helpful?

Solution

Do you mean log4cpp from http://sourceforge.net/projects/log4cpp/ ?

The short answer is yes.

Here are some sample codes, and you can figure out more details based on its doc:

My codes are used to configure file-based log4cpp instance at run-time.

"priority" is 'DEBUG', ...
"name" here is 'root'
"layout" could be "%d{%Y-%m-%d %H:%M:%S}%c %x: %m%n"

// Create RollingFileAppender
log4cpp::Appender *rfileAppender = new log4cpp::RollingFileAppender(std::string(name),
        std::string(fileName),
        maxFileSize,
        maxBackupIndex,
        append,
        mode);

if (rfileAppender != NULL)
{
    // Create PatternLayout
    log4cpp::Layout *layout = new log4cpp::PatternLayout();

    if (layout != NULL)
    {
        try
        {
            // Set up Pattern
            ((log4cpp::PatternLayout *)layout)->setConversionPattern(std::string(layoutPattern));

            // Bind Layout to RollingFileAppender
            rfileAppender->setLayout(layout);

            category.setAdditivity(additivity);

            try
            {
                category.setPriority(log4cpp::Priority::getPriorityValue(std::string(priority)));
            }
            catch(std::invalid_argument &ia)
            {
                std::cerr << "Invalid Priority: "  << priority << std::endl;
                category.setPriority(log4cpp::Priority::INFO);
            }

            // Bind RollingFileAppender to Category
            category.addAppender(rfileAppender);

            return 0;
        }
        catch(log4cpp::ConfigureFailure &cf)
        {
            std::cerr << cf.what() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cerr << "Cannot initialize PatternLayout" << std::endl;
        return 1;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top