贡献一个简单的日志类

不多解释,用到了log4cpp和boost库。

_GLIBCXX_BEGIN_NAMESPACE宏是c++标准库里的,用于声明namespace。我是从stl源码里拿过来用的。

 

 1 /*
 2  * File:   log.h
 3  * Author: raozf
 4  *
 5  * Created on 2012年7月19日, 上午11:33
 6  */
 7 
 8 #ifndef RZF_LOG_H
 9 #define RZF_LOG_H
10 
11 #include <boost/date_time/posix_time/posix_time.hpp>
12 #include <log4cpp/FileAppender.hh>
13 #include <log4cpp/Category.hh>
14 #include <log4cpp/PropertyConfigurator.hh>
15 
16 _GLIBCXX_BEGIN_NAMESPACE(Log)
17 class Log
18 {
19 public:
20     inline static Log& instance()
21     {
22         static Log l;
23         return l;
24     }
25 
26     inline log4cpp::Category* getCategory()
27     {
28         return p;
29     }
30 
31 private:
32     Log()
33     {
34         log4cpp::PropertyConfigurator::configure(std::string("log.conf"));
35         p = &log4cpp::Category::getRoot();
36     }
37 
38     log4cpp::Category* p;
39 };
40 
41 //to_simple_string
42 #define NOW boost::posix_time::to_iso_extended_string(boost::posix_time::microsec_clock::local_time())
43 #define LOG_DEBUG(msg) LOG4CPP_DEBUG_S((*Log::instance().getCategory()))<<"["<<NOW<<"][DEBUG]"<<msg;
44 #define LOG_INFO(msg) LOG4CPP_INFO_S((*Log::instance().getCategory()))<<"["<<NOW<<"][INFO]"<<msg;
45 #define LOG_WARN(msg) LOG4CPP_WARN_S((*Log::instance().getCategory()))<<"["<<NOW<<"][WARN]"<<msg;
46 #define LOG_ERROR(msg) LOG4CPP_ERROR_S((*Log::instance().getCategory()))<<"["<<NOW<<"][ERROR]"<<msg;
47 #define LOG_FATAL(msg) LOG4CPP_FATAL_S((*Log::instance().getCategory()))<<"["<<NOW<<"][FATAL]"<<msg;
48 
49 _GLIBCXX_END_NAMESPACE
50 #endif    /* RZF_LOG_H */

 

不足:

(1)如果打印日志非常频繁,可能会有性能问题。

(2)没有重复日志控制,如果在for,while之类的循环中打日志时,可能会打印大量重复日志。

posted @ 2012-07-23 17:05    阅读(371)  评论(0编辑  收藏  举报