Skip to content

Commit

Permalink
improve log module; get rid of global mutex object
Browse files Browse the repository at this point in the history
  • Loading branch information
kolomenkin committed May 13, 2022
1 parent 4da1e7e commit 67341a7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
11 changes: 9 additions & 2 deletions Logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@
#include <string_view>


std::mutex Logger::s_protect;
Logger::LogLevel Logger::m_minLogLevel = Logger::LogLevel::Debug;



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

if (logLevel < m_minLogLevel)
{
return;
}

std::string_view strLogLevel = "UNKNOWN"sv;
switch (logLevel)
{
Expand Down Expand Up @@ -46,7 +52,8 @@ void Logger::log(const std::string& message, const LogLevel logLevel)
gmtime_r(&tNow, &tmNow);
#endif

std::lock_guard lock(s_protect);
static std::mutex protect;
std::lock_guard lock(protect);

stream
<< std::put_time(&tmNow, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(3) << std::setfill('0') << std::right << milliseconds
Expand Down
13 changes: 12 additions & 1 deletion Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,18 @@ class Logger

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

static LogLevel GetLogLevel(const LogLevel level)
{
return m_minLogLevel;
}

static void SetLogLevel(const LogLevel level)
{
m_minLogLevel = level;
}

protected:
static std::mutex s_protect;
static LogLevel m_minLogLevel;
};

class LogStream
Expand Down Expand Up @@ -89,5 +99,6 @@ class LogStream
};


#define LOG_DEBUG LogStream(Logger::LogLevel::Debug)
#define LOG_INFO LogStream(Logger::LogLevel::Info)
#define LOG_ERROR LogStream(Logger::LogLevel::Error)
3 changes: 3 additions & 0 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

int main(const int argc, const char* const* const argv)
{
const Logger::LogLevel logLevel = Logger::LogLevel::Debug;
Logger::SetLogLevel(logLevel);

LOG_INFO << "main: begin" << std::endl;
const std::string arg1 = argc > 1 ? argv[1] : "";

Expand Down

0 comments on commit 67341a7

Please sign in to comment.