log4cplus使用

log4cplus is a simple to use C++ logging API providing thread-safe, flexible, and arbitrarily granular control over log management and configuration. It is modelled after the Java log4j API. 下载地址http://sourceforge.net/projects/log4cplus/

也可以看出Java/C++是互相借鉴的,没有好坏之分。

很详细的介绍在log4cplus学习笔记

本文记录在项目中的一个常用实例。

定义工具文件

Util.h

#include <log4cplus/logger.h>
#include <log4cplus/configurator.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/loggingmacros.h>
using namespace log4cplus;
using namespace log4cplus::helpers;
inline void InitLogger(
  const string& name = "PINGLOG",
  const string& path = "./log",
  const string& loglevel = "DEBUG",
  const string& pattern = "%-10D{%H:%M:%S.%q} : [%p] : %m%n")
{
  log4cplus::SharedAppenderPtr append_1(new log4cplus::DailyRollingFileAppender(path, log4cplus::HOURLY , 1, true));
  append_1->setName(name);
  append_1->setLayout( std::auto_ptr<log4cplus::Layout>(new log4cplus::PatternLayout(pattern)) );
  log4cplus::Logger::getInstance(name).addAppender(append_1);
  log4cplus::Logger::getInstance(name).setLogLevel(log4cplus::LogLevelManager().fromString(loglevel));
}

#define LOG_DEBUG(msg) \
  LOG4CPLUS_DEBUG(log4cplus::Logger::getInstance("PINGLOG"), msg)
#define LOG_INFO(msg) \
  LOG4CPLUS_INFO(log4cplus::Logger::getInstance("PINGLOG"), msg) 
#define LOG_WARN(msg) \
  LOG4CPLUS_WARN(log4cplus::Logger::getInstance("PINGLOG"), msg)

使用

#include "Util.h"
InitLogger();
LOG_INFO("test");
LOG_WARN("test" << " WARN");

注意:保存路径要具体到文件,如./log,就是保存到当前路径log文件中。

你可能感兴趣的:(log4cplus使用)