模仿glog风格的log实现
需求
实现一个类似glog风格支持<<链式调用的log库。
代码
#x
将文本转为字符串,__FILE__
获取文件名,__LINE__
获取行号。
利用析构函数特性,每行LOG结束后调用,完成日志消息拼接。
#include <string>
#include <iostream>
#include <cstring>
// set filename and line num as log header
#define __NAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define LOG(x) log(#x, __NAME__, __LINE__)
class log
{
public:
log(const std::string& level, const char* file, int line)
{
body = "[" + level + "][" + file + ":" + \
std::to_string(line) + "] " ;
}
template<typename type>
log& operator<<(type msg)
{
body += std::to_string(msg);
return *this;
}
log& operator<<(const char* msg)
{
body += msg;
return *this;
}
~log()
{
std::cout << body << std::endl;
}
private:
std::string body;
};
int main()
{
LOG(INFO) << "test" << 111;
LOG(WARN) <<"float: " << float(41*8 + 59%8)/640*1900;
return 0;
}
效果
[INFO][example.cpp:38] test111
[WARN][example.cpp:39] float: 982.656189