之前写的了个日志类,感觉写得比较啰嗦,重新写一个比较简单的,功能跟之前差不多.
<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.log
curr_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> : hello
1.2015-03-29T01:41:03.645214 <debug> : hi
2.2015-03-29T01:41:03.645214 <info> : hello
3.2015-03-29T01:41:03.645214 <debug> : hi
logger()构造一个匿名对象,这个临时的匿名对象调用debug(),info()等方法往文件里写,一个日志文件写满1M就再建一个,日志的文件名:log_0.log log_1.log log _2.log........