Skip to content

Commit 67341a7

Browse files
committed
improve log module; get rid of global mutex object
1 parent 4da1e7e commit 67341a7

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

Logger.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,19 @@
66
#include <string_view>
77

88

9-
std::mutex Logger::s_protect;
9+
Logger::LogLevel Logger::m_minLogLevel = Logger::LogLevel::Debug;
10+
1011

1112

1213
void Logger::log(const std::string& message, const LogLevel logLevel)
1314
{
1415
using namespace std::literals;
1516

17+
if (logLevel < m_minLogLevel)
18+
{
19+
return;
20+
}
21+
1622
std::string_view strLogLevel = "UNKNOWN"sv;
1723
switch (logLevel)
1824
{
@@ -46,7 +52,8 @@ void Logger::log(const std::string& message, const LogLevel logLevel)
4652
gmtime_r(&tNow, &tmNow);
4753
#endif
4854

49-
std::lock_guard lock(s_protect);
55+
static std::mutex protect;
56+
std::lock_guard lock(protect);
5057

5158
stream
5259
<< std::put_time(&tmNow, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(3) << std::setfill('0') << std::right << milliseconds

Logger.h

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,18 @@ class Logger
2121

2222
static void log(const std::string& message, const LogLevel logLevel);
2323

24+
static LogLevel GetLogLevel(const LogLevel level)
25+
{
26+
return m_minLogLevel;
27+
}
28+
29+
static void SetLogLevel(const LogLevel level)
30+
{
31+
m_minLogLevel = level;
32+
}
33+
2434
protected:
25-
static std::mutex s_protect;
35+
static LogLevel m_minLogLevel;
2636
};
2737

2838
class LogStream
@@ -89,5 +99,6 @@ class LogStream
8999
};
90100

91101

102+
#define LOG_DEBUG LogStream(Logger::LogLevel::Debug)
92103
#define LOG_INFO LogStream(Logger::LogLevel::Info)
93104
#define LOG_ERROR LogStream(Logger::LogLevel::Error)

main.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212

1313
int main(const int argc, const char* const* const argv)
1414
{
15+
const Logger::LogLevel logLevel = Logger::LogLevel::Debug;
16+
Logger::SetLogLevel(logLevel);
17+
1518
LOG_INFO << "main: begin" << std::endl;
1619
const std::string arg1 = argc > 1 ? argv[1] : "";
1720

0 commit comments

Comments
 (0)