log4cpp的使用
MyLogger.hh
#ifndef __MyLogger_HH__
#define __MyLogger_HH__
#include <log4cpp/CategoryStream.hh>
using namespace log4cpp;
class MyLogger
{
public:
static MyLogger * getInstance();
static void destroy();
void warn(const char *msg);
void error(const char *msg);
void debug(const char *msg);
void info(const char *msg);
private:
MyLogger();
~MyLogger();
private:
static MyLogger * _pInstance;
Category & _mycat;
};
#endif
MyLogger.cc
#include "MyLogger.hh"
#include <iostream>
#include <log4cpp/Category.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/FileAppender.hh>
using std::cout;
using std::endl;
using namespace log4cpp;
MyLogger * MyLogger::_pInstance = nullptr;
MyLogger * MyLogger::getInstance(){
if(_pInstance == nullptr){
_pInstance = new MyLogger();
}
return _pInstance;
}
void MyLogger::destroy(){
if(_pInstance){
delete _pInstance;
_pInstance = nullptr;
}
}
void MyLogger::warn(const char *msg){
_mycat.warn(msg);
}
void MyLogger::error(const char *msg){
_mycat.error(msg);
}
void MyLogger::debug(const char *msg){
_mycat.debug(msg);
}
void MyLogger::info(const char *msg){
_mycat.info(msg);
}
MyLogger::MyLogger()
: _mycat(Category::getRoot().getInstance("mycat"))
{
//日志布局
PatternLayout * ptn1 = new PatternLayout();
ptn1->setConversionPattern("%d %c [%p] %m%n");
PatternLayout * ptn2 = new PatternLayout();
ptn2->setConversionPattern("%d %c [%p] %m%n");
//日志目的地
auto pos = new OstreamAppender("console",&cout);
pos->setLayout(ptn1);
auto pfile = new FileAppender("fileApp","wd.log");
pfile->setLayout(ptn2);
//设置优先级
_mycat.setPriority(Priority::DEBUG);
//设置目的地
_mycat.addAppender(pos);
_mycat.addAppender(pfile);
cout << "MyLogger()" << endl;
}
MyLogger::~MyLogger(){
Category::shutdown();
cout << "~MyLogger()" << endl;
}
TestMyLogger.cc
#include "MyLogger.hh"
#include <iostream>
using std::cout;
using std::endl;
using std::string;
#if 0
string func(const char * msg){
string s = string(" [") +
string(__FILE__) + string(" ")
+ string(__func__) + string(" ")
+ string(std::to_string(__LINE__))
+ string("] ") + msg;
return s;
}
#endif
#define prefix(msg) (string(" [") +\
string(__FILE__) + string(" ")\
+ string(__func__) + string(" ")\
+ string(std::to_string(__LINE__))\
+ string("] ") + msg).c_str()
#define LogWarn(msg) MyLogger::getInstance()->info(prefix(msg))
void test0(){
/* MyLogger * plog = MyLogger::getInstance(); */
/* plog->info("hello"); */
/* plog->info(func("hello").c_str()); */
/* plog->info(prefix("this is an info msg")); */
MyLogger::getInstance()->info(prefix("hello"));
LogWarn("this is a warn msg");
}
void test1(){
cout << __FILE__ << endl;
cout << __func__ << endl;
cout << __LINE__ << endl;
}
int main(void){
test0();
/* test1(); */
return 0;
}```