From 5cdc743d491a04ee0446bd757cedb4c7b6bc585f Mon Sep 17 00:00:00 2001 From: Carlo Zancanaro Date: Mon, 9 Jul 2012 17:09:49 +1000 Subject: Cleaning up a bit of code around the place. - Especially making logging a bit nicer. --- impl/Log.hpp | 71 +++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 42 insertions(+), 29 deletions(-) (limited to 'impl/Log.hpp') diff --git a/impl/Log.hpp b/impl/Log.hpp index 1e340c7..0f12fec 100644 --- a/impl/Log.hpp +++ b/impl/Log.hpp @@ -1,50 +1,63 @@ #ifndef LOG_HPP #define LOG_HPP +// could not be hackier, but C++ is annoying +#define protected public +#include +#undef protected + #include -#include +#include #include namespace log { - struct Logger { - Logger(std::ostream& stream, const std::string& name) - : _stream(stream), - _name(name), - _enabled(false) {} + struct LoggerBuffer : public std::streambuf { + LoggerBuffer(std::streambuf* buffer, const std::string& name) + : _buffer(buffer), + _prefix(name + " :- "), + _prefix_next(true) { } + + int_type overflow(int_type c=EOF) { + if (_prefix_next) { + _buffer->sputn(_prefix.c_str(), _prefix.length()); + _prefix_next = false; + } + if (c == '\n') { + _prefix_next = true; + } + return _buffer->overflow(c); + } + private: + std::streambuf* _buffer; + std::string _prefix; + bool _prefix_next; + }; + + struct Logger : public std::ostream { + Logger(std::streambuf* buffer, const std::string& name) + : std::ostream(NULL), + _buffer(buffer, name) { } bool enabled() const { - return _enabled; + return rdbuf() != NULL; } bool enabled(bool v) { - bool ret = _enabled; - _enabled = v; + bool ret = enabled(); + rdbuf(v ? &_buffer : NULL); return ret; } - template - friend Logger& operator<<(Logger&, const T&); - - private: - std::ostream& _stream; - std::string _name; - bool _enabled; + private: + LoggerBuffer _buffer; }; - template - Logger& operator<<(Logger& logger, const T& obj) { - if (logger._enabled) { - logger._stream << logger._name << " :- " << obj << std::endl; - } - return logger; - } - - Logger info(std::cout, "info"); - Logger trace(std::cerr, "trace"); - Logger strategy(std::cerr, "strategy"); - Logger fixpoint(std::cerr, "fixpoint"); - Logger debug(std::cerr, "debug"); + Logger info(std::cout.rdbuf(), "info"); + Logger trace(std::cerr.rdbuf(), "trace"); + Logger strategy(std::cerr.rdbuf(), "strategy"); + Logger fixpoint(std::cerr.rdbuf(), "fixpoint"); + Logger debug(std::cerr.rdbuf(), "debug"); } -- cgit v1.2.3