码迷,mamicode.com
首页 > 其他好文 > 详细

简易的日志类

时间:2015-07-14 22:24:09      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

打日志是开发不可或缺的功能, 它经常比断点好用, 并且可用性更广.

在很久以前, 我总习惯性的printf, cout, 把日志打印在控制台.

直到我发现, 这除了针对性的看日志, 并没有什么乱用.

你的程序提交到测试那里, 程序出现意外, 你不能指望测试给你提供崩溃当时的日志, 也不能及时赶到现场, 发动写轮眼记下原因.

所以, 日志除了打印在屏幕, 还要写日到文件...

 1     //    日志写入.
 2     class Log {
 3     public:
 4         //    日志结束符.
 5         class End {};
 6 
 7         Log()
 8         {
 9         }
10 
11         ~Log()
12         {
13             _logfile.close();
14         }
15 
16         template <class T>
17         Log &operator <<(const T &value)
18         {
19             if (open())
20             {
21                 _osstream << value;
22             }
23             return *this;
24         }
25 
26         Log &operator <<(const End &e)
27         {
28             auto now = std::chrono::system_clock::now();
29             auto time = std::chrono::system_clock::to_time_t(now);
30             auto str = ctime(&time);
31             _osstream << "\n" << str << "\n";
32             const auto &logstr = _osstream.str();
33             _osstream.str("");
34             _logfile << logstr << std::endl;
35             cocos2d::log("[log] %s", logstr.c_str());
36             return *this;
37         }
38 
39     private:
40         bool open()
41         {
42             if (!_logfile.is_open())
43             {
44                 auto path = FileUtils::getInstance()->getWritablePath();
45                 auto full = path + "/game.log";
46                 _logfile.open(full, std::ios::app);
47 
48                 *this << "\n\n\n-----------------game begin-----------------" << End();
49             }
50             return !!_logfile;
51         }
52         std::ofstream        _logfile;
53         std::ostringstream    _osstream;
54     };

这是C++风格的日志类, 通过重载运算符 << 来对流写入.

通过重载 End 来执行打印, 写入.

这个End是一个空类, 它主要用于区分, 让其执行收尾工作.

写入的内容通过一个 stirngstream 保存, 并且在收尾的时候清空.

1 extern Log glog;
2 
3 glog << 123 << "|" << "hehehe" << Log::End;

咱们可以向上面这样使用.

在很多时候, 我们只需要一次写入一段字符串.

 

所以, 咱们可以定义一个宏.

extern lutils::Log glog;

#ifdef MMC_LOG
#define LLOG(str) \
    glog << __FILE__ << "|" << __LINE__ << "|" << str << lutils::Log::End()
#else
#define LLOG(str)
#endif

然后在需要的时候 LLOG("log1")..

这个LLOG通过MMC_LOG开关来控制...

 

简易的日志类

标签:

原文地址:http://www.cnblogs.com/mmc1206x/p/4646493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!