-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.cpp
98 lines (84 loc) · 1.86 KB
/
logger.cpp
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
93
94
95
96
97
98
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include "logger.h"
Logger::Logger(std::string filePath) :
myqueue(128),
done(false) {
this->fs.open(filePath, std::ofstream::trunc | std::ofstream::out);
if (!this->fs.is_open()) throw std::runtime_error("Can't open the file");
this->worker = std::thread(&Logger::work, this);
}
Logger::~Logger() {
this->done = true;
this->worker.join();
this->fs.close();
}
void Logger::write(std::string* text) {
if (text == nullptr) return;
this->fs << *text << std::endl;
delete text;
}
/*
void Logger::work() {
std::string *value;
while (!this->done) {
while (value = this->myqueue.front()) {
this->myqueue.pop();
this->write(value);
}
}
while (value = this->myqueue.front()) {
this->myqueue.pop();
this->write(value);
}
}
//*/
//*
void Logger::work() {
std::string *value;
while (!this->done) {
while (this->myqueue.pop(value)) {
this->write(value);
}
}
while (this->myqueue.pop(value)) {
this->write(value);
}
}
//*/
void Logger::message(MessageType type, std::string text) {
std::string sType;
switch(type) {
case MessageType::WARNING:
sType = "WARN";
break;
case MessageType::INFO:
sType = "INFO";
break;
case MessageType::ERROR:
sType = "ERR ";
break;
default:
sType = "UNKN";
}
std::string *output = new std::string(this->getDateTime() +
" - " + sType + " - " + text);
this->myqueue.push(output);
}
void Logger::warning(std::string text) {
this->message(MessageType::WARNING, text);
}
void Logger::error(std::string text) {
this->message(MessageType::ERROR, text);
}
void Logger::info(std::string text) {
this->message(MessageType::INFO, text);
}
std::string Logger::getDateTime() {
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::stringstream ss;
ss << std::put_time(&tm, "%c %Z");
return ss.str();
}