Loading

模仿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

参考

c - FILE macro shows full path - Stack Overflow

posted @ 2024-09-20 15:30  azureology  阅读(7)  评论(0编辑  收藏  举报