您的位置:首页 > 其它

重新写了一个简单的日志类

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........

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: