-
Notifications
You must be signed in to change notification settings - Fork 3
/
lazylogger.hpp
70 lines (60 loc) · 1.49 KB
/
lazylogger.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
#ifndef __LAZYLOGGER_HPP__
#define __LAZYLOGGER_HPP__
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
class Logger {
private:
std::mutex mtx;
static std::mutex initMtx;
std::ofstream f;
static Logger *logger;
Logger() = default;
~Logger() = default;
public:
static Logger *instance() {
static Cleaner cleaner;
std::lock_guard<std::mutex> lock(Logger::initMtx);
if (logger == nullptr) {
logger = new Logger;
}
return logger;
}
static void init(const std::string &filename) {
std::lock_guard<std::mutex> lock(instance()->mtx);
if (instance()->f.is_open()) {
throw std::runtime_error{ "Logger already initialized" };
}
instance()->f.open(filename, std::ios::binary | std::ios::app);
}
Logger(const Logger &) = delete;
Logger& operator=(const Logger &) = delete;
void out(const std::string &msg) {
std::lock_guard<std::mutex> lock(mtx);
if (!instance()->f.is_open()) {
throw std::runtime_error{ "Logger not initialized" };
}
time_t t = time(nullptr);
std::stringstream ss;
ss << std::put_time(localtime(&t), "%Y-%m-%dT%H:%M:%S ")
<< msg << std::endl;
f << ss.str();
f.flush();
}
void flush() {
std::lock_guard<std::mutex> lock(mtx);
f.flush();
}
class Cleaner {
public:
~Cleaner() {
if (Logger::logger != nullptr) {
delete Logger::logger;
Logger::logger = nullptr;
}
}
};
};
#endif // __LAZYLOGGER_HPP__