您的位置:首页 > 编程语言 > C语言/C++

C++实现Log()日志函数

2015-06-25 18:33 555 查看
转载请注明原创:http://www.cnblogs.com/StartoverX/p/4600649.html

需求:Log()函数,能够自动根据时间记录日志信息,要求不定参数类型和参数个数。

第一步,得到日志时间:

  get_data() 和get_time()分别得到当前日期和时间。

#include <ctime>
static std::string get_data()
{
time_t t = time(0);
struct tm *now = localtime(&t);
std::stringstream ss;
ss<<now->tm_year+1900<<'_'
<<now->tm_mon+1<<"_"
<<now->tm_mday;
return ss.str();
}

static std::string get_time()
{
time_t t = time(0);
struct tm* now = localtime(&t);
std::stringstream ss;
ss<<get_data()<<' ';
ss<<now->tm_hour<<':'
<<now->tm_min<<':'
<<now->tm_sec;
return ss.str();
}


2.to_string()

  C++中,我们使用可变参数模板实现不定参数。

  首先实现to_string()参数将Log()中的参数全部传递至streamstring。to_string()通过递归的方式实现。

#include <string>
#include <sstream>

template <typename T>
static int to_string(std::stringstream& ss,const T &t)
{
ss<<t;
return 1;
}

template <typename T,typename...Args>
static int to_string(std::stringstream& ss,const T &t,const Args&...rest)
{
ss<<t;
return to_string(ss,rest...);
}


3.Log()

最后Log()调用上面三个函数,get_data()得到当天的时间找到对应的日志文件,to_string()将日志内容和get_time()时间结合后输入到日志文件中。

template <typename T,typename...Args>
static int Log(const T &t,const Args&...rest)
{
std::stringstream ss;
to_string(ss,t,rest...);
std::string path = LOG_PATH;
path +=get_data();        //日志名字为当天时间
std::fstream log_file;
log_file.open(path,std::ios::out|std::ios::app);
log_file<<"["<<get_time()<<"]"<<ss.str()<<std::endl;
log_file.close();
std::cerr<<ss.str()<<std::endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: