summaryrefslogtreecommitdiff
path: root/impl/Log.hpp
diff options
context:
space:
mode:
authorCarlo Zancanaro <carlo@pc-4w14-0.cs.usyd.edu.au>2012-07-09 17:09:49 +1000
committerCarlo Zancanaro <carlo@pc-4w14-0.cs.usyd.edu.au>2012-07-09 17:09:49 +1000
commit5cdc743d491a04ee0446bd757cedb4c7b6bc585f (patch)
treef9096fd6a5b8c8c9ec33719158a3d7ffdf3b25df /impl/Log.hpp
parent8040a5fd511912cb2141e46e5ca9eb1ab766133e (diff)
Cleaning up a bit of code around the place.
- Especially making logging a bit nicer.
Diffstat (limited to 'impl/Log.hpp')
-rw-r--r--impl/Log.hpp71
1 files changed, 42 insertions, 29 deletions
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 <streambuf>
+#undef protected
+
#include <string>
-#include <ostream>
+#include <iostream>
#include <map>
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<typename T>
- friend Logger& operator<<(Logger&, const T&);
-
- private:
- std::ostream& _stream;
- std::string _name;
- bool _enabled;
+ private:
+ LoggerBuffer _buffer;
};
- template<typename T>
- 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");
}