Merge branch 'release-2.1.0'
[purplehaze.git] / src / log.h
blob4cda6c680fbf2e1bfc8046c51de9d35e7d136820
1 /* Copyright (C) 2007-2012 Vincent Ollivier
3 * Purple Haze is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
8 * Purple Haze is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #ifndef LOG_H
18 #define LOG_H
20 #include <iostream>
21 #include <fstream>
23 class Log : public std::ostream
25 private:
26 template <class T>
27 struct LogStream {
28 T stream;
29 bool state;
31 LogStream() :
32 stream(),
33 state(false)
35 LogStream(std::streambuf *sb) :
36 stream(sb),
37 state(true)
39 LogStream(std::string filename) :
40 stream(filename, std::ios::app),
41 state(true)
44 LogStream<std::ostream> cout;
45 LogStream<std::ofstream> file;
47 public:
48 enum Stream { COUT, FILE, BOTH };
49 enum LogDirection { IN, OUT, DEBUG };
51 Log() :
52 std::ostream(std::cout.rdbuf()),
53 cout(std::cout.rdbuf()),
54 file()
57 Log(std::string filename) :
58 std::ostream(std::cout.rdbuf()),
59 cout(std::cout.rdbuf()),
60 file(filename)
63 void open(std::string filename) {
64 file.stream.open(filename, std::ios::app);
65 file.state = true;
68 template <typename T>
69 Log& operator<<(const T &val) {
70 if (cout.state) {
71 cout.stream << val;
73 if (file.state && file.stream.is_open()) {
74 file.stream << val;
76 return *this;
79 Log& operator<<(std::ostream& (*manip)(std::ostream&)) {
80 if (cout.state) {
81 cout.stream << manip;
83 if (file.state && file.stream.is_open()) {
84 file.stream << manip;
86 return *this;
89 Log& operator<<(const LogDirection &dir);
90 Log& to(Stream s);
92 #endif /* !LOG_H*/