C++实现Log()日志函数
2015-06-25 18:33
555 查看
转载请注明原创:http://www.cnblogs.com/StartoverX/p/4600649.html
需求:Log()函数,能够自动根据时间记录日志信息,要求不定参数类型和参数个数。
第一步,得到日志时间:
get_data() 和get_time()分别得到当前日期和时间。
2.to_string()
C++中,我们使用可变参数模板实现不定参数。
首先实现to_string()参数将Log()中的参数全部传递至streamstring。to_string()通过递归的方式实现。
3.Log()
最后Log()调用上面三个函数,get_data()得到当天的时间找到对应的日志文件,to_string()将日志内容和get_time()时间结合后输入到日志文件中。
需求: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; }
相关文章推荐
- C++中的头文件和源文件
- 第十六周oj刷题——Problem A: C++类实现最大数的输出
- 第十五周oj刷题——Problem N: C++习题 复数类--重载运算符3+
- GoogleCpp风格指南 8)格式 _part1
- C语言中存储类型和Static关键字
- C++ int与string的转化
- C语言数组学习
- STM8S之时钟设置
- 面试题48:用C++设计一个不能被继承的类
- 进程、线程同步互斥学习 —— 信号量
- C++/C笔试面试题目大大的集合
- C++语言债券系列之十一——友元函数和拷贝构造函数
- C++模板
- Java调用c++的方法
- 学习C++ 模板类
- 指针
- C++ stringstream 用法
- gdb调试c++的STL容器
- C++入门学习——标准模板库之vector
- Effective C++ 条款19