美文网首页
Simple Glog

Simple Glog

作者: Jonah_Peng | 来源:发表于2021-04-22 16:24 被阅读0次
    #include <iostream>
    #include <sstream>
    
    #define DEBUG 1
    #define INFO 2
    #define WARNING 3
    
    /**
     * https://stackoverflow.com/questions/17595957/operator-overloading-in-c-for-logging-purposes
     */
    class Logger {
    private:
        /**
         * 引用类型必须使用:初始化列表来初始化
         */
        std::ostream& out_stream;
    
    public:
        explicit Logger(int level, std::ostream& stream = std::cout) :
                out_stream(stream) {
            if (level == 1) {
                out_stream << "[DEBUG]";
            } else if (level == 2) {
                out_stream << "[INFO]";
            } else if (level == 3) {
                out_stream << "[WARNING]";
            }
        }
    
        ~Logger() {
            out_stream << std::endl;
        }
    
        template <typename T>
        Logger& operator<<(const T& data) {
            out_stream << data;
            return *this;
        }
    };
    
    #define LOG(level) Logger(level)
    
    void test_log() {
        LOG(INFO) << "info";
        LOG(WARNING) << "warn";
    }
    
    int main(int argc, char** argv) {
        test_log();
    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:Simple Glog

          本文链接:https://www.haomeiwen.com/subject/oikfrltx.html