#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;
}
网友评论