如何以编程方式配置log4cpp?

时间:2012-06-29 09:52:07

标签: configuration log4cpp

是否可以以编程方式配置log4cpp?

我想通过提供以下配置文件来配置它。

appender root basic console
priority root DEBUG

1 个答案:

答案 0 :(得分:2)

您的意思是来自http://sourceforge.net/projects/log4cpp/的log4cpp吗?

简短的回答是肯定的。

以下是一些示例代码,您可以根据其文档了解更多详细信息:

我的代码用于在运行时配置基于文件的log4cpp实例。

“priority”是'DEBUG',...
这里的“名字”是“根” “布局”可以是“%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;
    }
}