对 log4cplus 库的封装,修改自网路
LogUtils.h
/*
* LogUtils.h
*
* Created on: 2018年8月9日
* Author: oftenlin
*/ #ifndef UTILS_LOGUTILS_H_
#define UTILS_LOGUTILS_H_
// LogUtils.h: interface for the LogUtils class.
//
////////////////////////////////////////////////////////////////////// #include "log4cplus/loglevel.h"
#include "log4cplus/ndc.h"
#include "log4cplus/logger.h"
#include "log4cplus/configurator.h"
#include "iomanip"
#include "log4cplus/fileappender.h"
#include "log4cplus/layout.h"
#include <log4cplus/loggingmacros.h> using namespace log4cplus;
using namespace log4cplus::helpers; #define PATH_SIZE 100
//日志封装
#define TRACE(p) LOG4CPLUS_TRACE(LogUtils::_logger, p)
#define DEBUG(p) LOG4CPLUS_DEBUG(LogUtils::_logger, p)
#define NOTICE(p) LOG4CPLUS_INFO(LogUtils::_logger, p)
#define WARNING(p) LOG4CPLUS_WARN(LogUtils::_logger, p)
#define FATAL(p) LOG4CPLUS_ERROR(LogUtils::_logger, p) // 日志控制类,全局共用一个日志
class LogUtils
{
public:
// 打开日志
bool open_log(); // 获得日志实例
static LogUtils& instance(); static Logger _logger; private:
LogUtils(); virtual ~LogUtils(); //log文件路径及名称
char _log_path[PATH_SIZE];
char _log_name[PATH_SIZE];
}; #endif /* UTILS_LOGUTILS_H_ */
LogUtils.cpp
/*
* LogUtils.cpp
*
* Created on: 2018年8月9日
* Author: oftenlin
*/ // Log.cpp: implementation of the Log class.
//
////////////////////////////////////////////////////////////////////// #include "LogUtils.h"
#include <memory> //////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// Logger LogUtils::_logger = log4cplus::Logger::getInstance("main_log"); LogUtils::LogUtils()
{
snprintf(_log_path, sizeof(_log_path), "%s", "./log");
snprintf(_log_name, sizeof(_log_name), "%s/%s.%s", _log_path, "app", "log");
} LogUtils::~LogUtils()
{
} LogUtils& LogUtils::instance()
{
static LogUtils log;
return log;
} bool LogUtils::open_log()
{ int Log_level = ; /* step 1: Instantiate an appender object */
SharedAppenderPtr _append(new FileAppender(_log_name));
_append->setName("file log test"); /* step 2: Instantiate a layout object */
std::string pattern = "[%p] [%d{%m/%d/%y %H:%M:%S}] [%t] - %m %n";
std::auto_ptr<Layout> _layout(new PatternLayout(pattern)); // std::auto_ptr<Layout> pTTCLayout(new TTCCLayout());
/* step 3: Attach the layout object to the appender */
_append->setLayout(_layout);
// _append->setLayout(pTTCLayout);
/* step 4: Instantiate a logger object */ /* step 5: Attach the appender object to the logger */
LogUtils::_logger.addAppender(_append); /* step 6: Set a priority for the logger */
LogUtils::_logger.setLogLevel(Log_level); return true;
}