-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlog.hpp
92 lines (73 loc) · 1.42 KB
/
log.hpp
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
86
87
88
89
90
91
92
#pragma once
#include <functional>
#include <string>
#include <ostream>
#include <string.h>
namespace kvak::log {
// TODO: This (everything here) is somewhat fragile
class perror_class {};
extern perror_class perror;
static inline std::ostream &operator<<(std::ostream &os, const perror_class pr)
{
return os << " : " << strerror(errno);
}
class log_wrapper {
public:
log_wrapper(const std::string &prefix, std::ostream &stream)
:
prefix(prefix),
stream(stream)
{
}
class log_ender {
public:
log_ender()
{
}
log_ender(std::ostream &stream)
:
stream(stream)
{
}
~log_ender()
{
if (this->stream) {
this->stream.value().get() << "\x1b[0m" << std::endl;
}
}
template<typename T>
log_ender &operator<<(T &&val)
{
if (this->stream) {
this->stream.value().get() << val;
}
return *this;
}
private:
std::optional<std::reference_wrapper<std::ostream>> stream;
};
void mute()
{
this->stream.reset();
}
void redirect(std::ostream &stream)
{
this->stream = stream;
}
template<typename T>
log_ender operator<<(T &&val)
{
// TODO: This requires some major unhackify-ing
if (!this->stream) {
return log_ender();
}
return log_ender(this->stream.value().get() << this->prefix << val);
}
private:
std::string prefix;
std::optional<std::reference_wrapper<std::ostream>> stream;
};
extern log_wrapper debug;
extern log_wrapper info;
extern log_wrapper error;
}