-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiniLog.hpp
123 lines (115 loc) · 2.75 KB
/
MiniLog.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#pragma once
#include <mutex>
#include <queue>
#include <stdarg.h>
#include <memory>
#include <mutex>
#include <thread>
#include <condition_variable>
#include "utils.h"
#define minilog(level, fmt, ...) \
do \
{ \
Logger::GetInstance()->Log(level, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__); \
} while (0)
enum class LogLevel_e
{
INFO = 0,
DEBUG,
WARRNIG,
ERROR
};
static std::string convert_level_to_string(LogLevel_e level)
{
std::string levelStr;
switch (level)
{
case LogLevel_e::INFO:
levelStr = "INFO";
break;
case LogLevel_e::DEBUG:
levelStr = "DEBUG";
break;
case LogLevel_e::WARRNIG:
levelStr = "WARRNING";
break;
case LogLevel_e::ERROR:
levelStr = "ERROR";
break;
default:
break;
}
return levelStr;
}
class Logger
{
public:
Logger(const Logger &) = delete;
Logger operator=(const Logger &) = delete;
static std::shared_ptr<Logger> GetInstance();
void Log(LogLevel_e level, const char *file, const char *func, int line, const char *format, ...);
void Work();
private:
Logger()
{
_thread = std::thread(&Logger::Work, this);
_running = true;
}
~Logger()
{
_running = false;
_queueCv.notify_all();
_thread.join();
}
static std::shared_ptr<Logger> _inst;
std::mutex _queueMutex;
std::condition_variable _queueCv;
std::queue<std::string> _queue;
std::thread _thread;
bool _running;
};
std::shared_ptr<Logger> Logger::_inst = std::shared_ptr<Logger>(new Logger, [](Logger *p)
{ delete p; });
std::shared_ptr<Logger> Logger::GetInstance()
{
return _inst;
}
void Logger::Log(LogLevel_e level, const char *file, const char *func, int line, const char *format, ...)
{
char variaty[1024];
va_list args;
va_start(args, format);
vsprintf(variaty, format, args);
va_end(args);
char res[2048];
sprintf(res, "[%s] [%s:%d - %s] %s\n", convert_level_to_string(level).c_str(), file, line, func, variaty);
std::string oneLog = res;
{
std::lock_guard<std::mutex> lock(_queueMutex);
_queue.push(std::move(oneLog));
}
_queueCv.notify_all();
}
void Logger::Work()
{
while (_running)
{
// _queueMutex.lock();
// while(_queue.empty())
// {
// _queueMutex.unlock();
// _ququeCv.wait();
// }
// _queueMutex.lock();
// std::string &log = _queue.front();
// _queue.pop();
// _queueMutex.unlock();
std::unique_lock<std::mutex> lock(_queueMutex);
_queueCv.wait(lock, [this](){ return !(this->_queue.empty()) || !this->_running;});
if(!_queue.empty()){
std::string &log = _queue.front();
printf("%s", log.c_str());
_queue.pop();
}
}
}