log4cplus 直接创建logger 对象

时间:2023-12-26 09:30:37
#include <log4cplus/loggingmacros.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/consoleappender.h>
#include <log4cplus/logger.h>
#include <log4cplus/configurator.h>

using namespace log4cplus;
using namespace log4cplus::helpers;

void CreateLogConsole(const char *strLogName)
{
    // 1、生成一个appender 对象
    SharedAppenderPtr pConsoleAppender(new ConsoleAppender());

    // 2、生成layout 对象并绑定到appender
    std::auto_ptr<Layout> pLayout(new SimpleLayout());
    pConsoleAppender->setLayout(pLayout);

    // 3、生成logger 对象
    Logger logSuyh = Logger::getInstance(LOG4CPLUS_TEXT(strLogName));

    // 4、设置Logger 优先级
    logSuyh.setLogLevel(ALL_LOG_LEVEL);

    // 5、将需要关联的Logger 的Appender 添加到Logger 上
    logSuyh.addAppender(pConsoleAppender);

    // 6、使用Logger
    LOG4CPLUS_ERROR(logSuyh, "Console self suyh.log");
    LOG4CPLUS_ERROR_FMT(logSuyh, , "string text.");
}

void CreateLogFile(const char *strLogName, const char *strLogDir, const char *strLogFile)
{
    // 1、生成一个appender 对象
    MIFileAppender *miAppender = new MIFileAppender(LOG4CPLUS_TEXT(strLogDir));
    miAppender->init(strLogFile, );
    SharedAppenderPtr pAppender(miAppender);

    // 2、生成layout 对象并绑定到appender
    std::auto_ptr<Layout> pLayout(new SimpleLayout());
    pAppender->setLayout(pLayout);

    // 3、生成logger 对象
    Logger logSuyh = Logger::getInstance(LOG4CPLUS_TEXT(strLogName));

    // 4、设置Logger 优先级
    logSuyh.setLogLevel(ALL_LOG_LEVEL);

    // 5、将需要关联的Logger 的Appender 添加到Logger 上
    // 这里可以添加多个appender ,这样只要用该strLogName 的Logger 对象输出的日志将会
    // 同时输出到所有的appender 指定的文件或者控制台上
    logSuyh.addAppender(pAppender);

    // 6、使用Logger
    LOG4CPLUS_ERROR(logSuyh, "Log file self suyh.log");
}

int main()
{
    CreateLogFile("suyh_01", "suyh_log_dir", "log_file_01");
    CreateLogFile("suyh_02", "suyh_log_dir", "log_file_02");
    CreateLogFile("suyh_03", "suyh_log_dir", "log_file_03");

    log4cplus::Logger logSuyh01 = log4cplus::Logger::getInstance("suyh_01");
    log4cplus::Logger logSuyh02 = log4cplus::Logger::getInstance("suyh_02");
    log4cplus::Logger logSuyh03 = log4cplus::Logger::getInstance("suyh_03");

    LOG4CPLUS_INFO(logSuyh01, "log4cplus suyh01 log text...");
    LOG4CPLUS_INFO(logSuyh02, "log4cplus suyh02 log text...");
    LOG4CPLUS_INFO(logSuyh03, "log4cplus suyh03 log text...");

    ;
}