log4cpp 使用笔记

  1. 到官网下载https://sourceforge.net/projects/log4cpp/files/
  2. 下载后解压,打开msvc10,使用vs2010及以上版本进行编译(log4cpp是我目前碰到过最好编译的开源软件)
  3. 将include文件夹拷贝至需要使用的项目中,剩下的使用和其他库一致
  4. 添加一个日志工具类 CLogUtil
/**LogUtil.h**/
#pragma once

#include <iostream>
using namespace std;

class CLogUtil
{
public:
    static   int init(string initFileName = "./log4cpp.conf");
    static   void close();
    /// debug
    static   void d(string Tag, string msg);
    /// debug
    static   void D(string Tag, string msg);

    static   void info(string msg);
    static   void error(string msg);
};

/**LogUtil.cpp**/
#include "LogUtil.h"

#include <log4cpp/Category.hh>
//#include <log4cpp/Appender.hh>
//#include <log4cpp/FileAppender.hh>
//#include <log4cpp/Priority.hh>
//#include <log4cpp/PatternLayout.hh>
//#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/PropertyConfigurator.hh>

int CLogUtil::init(string initFileName) {
    try {

        log4cpp::PropertyConfigurator::configure(initFileName);
    }
    catch (log4cpp::ConfigureFailure&f) {
        std::cout << "Configure Problem " << f.what() << std::endl;
        return -1;
    }
    return 0;
}

void CLogUtil::close() {
    log4cpp::Category::shutdown();
}

/// debug
void CLogUtil::d(string Tag, string msg) {
    log4cpp::Category&sub1 = log4cpp::Category::getInstance(Tag);// GetCategory(Tag);
    LOG4CPP_DEBUG(sub1, msg);
}

/// debug
void CLogUtil::D(string Tag, string msg) {
    d(Tag, msg);
}

void CLogUtil::info(string msg)
{
    log4cpp::Category&sub1 = log4cpp::Category::getInstance(std::string("sub1"));
    sub1.info(msg);
}

void CLogUtil::error(string msg)
{
    log4cpp::Category&sub1 = log4cpp::Category::getRoot();// GetCategory(Tag);
    sub1.error(msg);
}
  1. 配置文件log4cpp.conf
# a simple test config 

#定义了3个category sub1, sub2, sub1.sub2 log4j.root
log4cpp.rootCategory=DEBUG, rootAppender 
log4cpp.category.sub1=,A1 
log4cpp.category.sub1.sub2=INFO,A2

# 设置sub1.sub2 的additivity属性 
#log4cpp.additivity.sub1=false
#log4cpp.additivity.sub1.sub2=false

#定义rootAppender类型和layout属性 
log4cpp.appender.rootAppender=ConsoleAppender 
log4cpp.appender.rootAppender.layout=PatternLayout
log4cpp.appender.rootAppender.layout.ConversionPattern=[%p] %d{%H:%M:%S.%l} (%c) %t : %m%n

#定义A1的属性 
log4cpp.appender.A1=FileAppender 
log4cpp.appender.A1.fileName=A1.log 
log4cpp.appender.A1.layout=SimpleLayout

#定义A2的属性 
log4cpp.appender.A2=RollingFileAppender
log4cpp.appender.A2.fileName=./log/A2.log
log4cpp.appender.A2.layout=PatternLayout 
log4cpp.appender.A2.layout.ConversionPattern=The message '%m' at time %d%n  
  1. 使用
int main(int argc, char **argv) {
    CLogUtil::init();
    CLogUtil::info("info!");
    CLogUtil::error("error!");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值