-
Notifications
You must be signed in to change notification settings - Fork 11
/
logger.h
74 lines (60 loc) · 1.39 KB
/
logger.h
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
#ifndef REPLICATOR_LOGGER_H
#define REPLICATOR_LOGGER_H
#include <unistd.h>
#include <time.h>
#include <iostream>
#include <sstream>
namespace replicator {
// originally found on stackoverflow
class Logger : public std::streambuf
{
public:
Logger( std::basic_ios< char >& out, char level ) : out(out), sink(), newline(true), level(level)
{
sink = out.rdbuf(this);
}
~Logger()
{
out.rdbuf(sink);
}
std::streambuf *rdsink() const {
return sink;
}
void rdsink(std::streambuf *sink) {
this->sink = sink;
}
protected:
int_type overflow( int_type m = traits_type::eof() )
{
if( traits_type::eq_int_type( m, traits_type::eof() ) )
return sink->pubsync() == -1 ? m: traits_type::not_eof(m);
if( newline )
{
std::ostream str( sink );
char timestr[64];
::time_t t;
struct ::tm bdtime;
t = ::time(NULL);
localtime_r(&t, &bdtime);
::strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", &bdtime);
if( !(str << "[" << timestr << "] " << level << " " ) ) {
return traits_type::eof(); // error
}
}
newline = traits_type::to_char_type( m ) == '\n';
int_type res = sink->sputc( m );
if (newline) {
sink->pubsync();
}
return res;
}
private:
Logger( const Logger& );
Logger& operator=( const Logger& ); // not copyable
std::basic_ios< char >& out;
std::streambuf* sink;
bool newline;
char level;
};
} // replicator
#endif // REPLICATOR_LOGGER_H