重新写了一个简单的日志类
2015-03-29 01:35
183 查看
之前写的了个日志类,感觉写得比较啰嗦,重新写一个比较简单的,功能跟之前差不多.<pre name="code" class="cpp">#ifndef LOGGING#define LOGGING#include<string>#include<fstream>#include<boost/filesystem.hpp>#include<boost/date_time.hpp>#include<boost/thread.hpp>namespace logging {static const long long MAXSIZE = 1024*1024; //最大尺寸using namespace std;using namespace boost;class log_abstract{public:virtual void write_log(const string mess) = 0;};class log_simple: public log_abstract{public:log_simple();void write_log (const string mess);private:fstream log_file; //文件int file_no; //文件名号int curr_line; //行号string curr_name; //当前名boost::mutex lock;void creat_logfile(const string filename = "log_");long long size();};log_simple::log_simple(){file_no = 0;creat_logfile ();}void log_simple::creat_logfile(const string filename){log_file.close ();curr_name = filename + to_string (file_no) + ".log"; //log_1.logcurr_line = 0;log_file.open (curr_name,ios_base::out);}long long log_simple::size(){return boost::filesystem::file_size (curr_name);}void log_simple::write_log(const string mess){if (MAXSIZE < size()){++file_no;creat_logfile ();}string message = to_string (curr_line) + "."+ boost::posix_time::to_iso_extended_string (boost::posix_time::microsec_clock::local_time())+ mess;boost::mutex::scoped_lock l(lock);++curr_line;log_file << message;}class logger{public:logger();void debug(const string messages);void info(const string messages); //只实现了两个方法.其它方法类似static log_abstract* log_singleton_ptr;};log_abstract* logger::log_singleton_ptr = nullptr;logger::logger(){if (!log_singleton_ptr) //单件模式,全局只有一个log_simple实例log_singleton_ptr = new log_simple(); //这里可能有一个很小的时间窗口,当一个线程运行到上一句.然后切换到另一个线程,也是运行到这里//就会调用两次NEW,只有第一次初始化才有机会遇上,机率应该比较小}void logger::debug(const string messages){string format = " <debug> : " + messages + '\n';log_singleton_ptr->write_log (format);}void logger::info(const string messages){string format = " <info> : " + messages + '\n';log_singleton_ptr->write_log (format);}}#endif // LOGGING用法和测试:
#include"logging.h" int main() { using namespace logging; while(1){ logger().debug ("hi"); logger().info ("hello"); auto log = logger(); log.debug ("hi"); log.debug ("hello");//在不同的线程 } }输出格式:0.2015-03-29T01:41:03.645214 <info> : hello1.2015-03-29T01:41:03.645214 <debug> : hi2.2015-03-29T01:41:03.645214 <info> : hello3.2015-03-29T01:41:03.645214 <debug> : hilogger()构造一个匿名对象,这个临时的匿名对象调用debug(),info()等方法往文件里写,一个日志文件写满1M就再建一个,日志的文件名:log_0.log log_1.log log _2.log........
相关文章推荐
- Log4J 做一个简单的日志工具
- 一个简单的日志类,测试时候用
- 一个简单又高效的日志系统
- 一个简单实用的C#日志类(第二版)
- 重新一步一步学习Lucene.NET 一个简单的程序开始(1)
- 重新整理一个简单的JS日历控件
- 一个用hibernate+struts写的简单日志系统
- 一个基于log4cplus的简单日志类
- 公布一个简单的日志记录方法 【转】-要研究
- 一个简单的C#文件日志组件
- 一个简单的linux下写日志的类
- 一个简单实用的C#日志类(第一版)
- 分享一个简单的日志记录静态类
- 一个简单的日志跟踪工具
- 一个简单的自定义程序日志小样例
- C#2005 一个简单的写日志类
- 一个简单的办法,把TreeView重新排版,把叶子节点横向排版.
- 公布一个简单的日志记录方法
- 一个简单的用于嵌入式Linux开发的C调试日志打印接口
- 一个简单的日志类