blob: cfc4d4cf98c80c304e25108e34369a3ca2b439ce (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
#pragma once
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
class log_stream
{
public:
log_stream(): m_active(false), m_buffer(), m_log_lines() {}
void log_lines(int n) {
m_log_lines = n;
}
std::string get_log() {
return m_buffer.str();
}
// log to buffer
void activate()
{
m_active = true;
}
// log to plain console
void deactivate()
{
m_active = false;
}
template<typename T>
log_stream& operator<<(const T& arg) {
if (m_active) {
m_buffer << arg;
trim_buffer();
}
else
{
std::cout << arg;
}
return *this;
}
log_stream& operator<<(
std::basic_ostream<char>& (*func)
(std::basic_ostream<char>&) ) {
if (m_active) {
m_buffer << *func;
trim_buffer();
}
else
{
std::cout << *func;
}
return *this;
}
private:
void trim_buffer()
{
std::string s = m_buffer.str();
size_t pos = s.npos;
for (int i = 0; i <= m_log_lines; ++i) {
pos = s.rfind("\n", pos);
if (pos == s.npos) {
// too few lines
return;
}
if (pos > 0) {
--pos;
}
}
m_buffer.str(s.substr((pos <= (s.size() - 2)) ? pos + 2 : pos));
}
bool m_active;
std::stringstream m_buffer;
int m_log_lines;
};
extern log_stream log_cout;
|