自定义Log4cpp的日志输出格式

时间:2021-05-27 06:44:12

// 1. 实例化一个PatternLayout对象
log4cpp::PatternLayout* pLayout = new log4cpp::PatternLayout();
// 2. 实例化一个RollingFileAppender对象
log4cpp::RollingFileAppender* rollingAppender = new log4cpp::RollingFileAppender("RollingFileAppender",path);
pLayout->setConversionPattern("%d:[%t][%05p] %c %x- %m%n");
// 3. 把pLayout对象附着在rollingAppender对象上   
rollingAppender->setLayout(pLayout);
// 4. 实例化一个category对象
log4cpp::Category& logcat = log4cpp::Category::getInstance(CATRGORY_NAME);
// 5. 设置additivity为false,替换已有的appender
logcat.setAdditivity(false);
// 5. 把appender对象附到category上
logcat.setAppender(rollingAppender);
// 6. 设置category的优先级,低于此优先级的日志不被记录
switch (level)
{
case DebugLevel:
    logcat.setPriority(log4cpp::Priority::DEBUG);
    break;
case InfoLevel:
    logcat.setPriority(log4cpp::Priority::INFO);
    break;
case WarnLevel:
    logcat.setPriority(log4cpp::Priority::WARN);
    break;
case ErrLevel:
    logcat.setPriority(log4cpp::Priority::ERROR);
    break;
default:
    logcat.setPriority(log4cpp::Priority::INFO);
    break;
}

// 记录开始日志
logcat.alert("-------------Init-------------");