0

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

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

appender root basic console
priority root DEBUG
4

1 回答 1

2

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

简短的回答是肯定的。

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

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

"priority" 是 'DEBUG', ...
"name" 这里是 'root'
"layout" 可能是 "%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;
    }
}
于 2013-01-28T15:45:12.693 回答