File size: 1,161 Bytes
d88fd8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @file logger.cpp
 */

#include "utils/logger.hpp"
#include <unordered_map>
#include <mutex>

namespace app::utils {

static std::unordered_map<std::string, Logger> loggers;
static std::mutex logger_mutex;

static const char* level_to_string(LogLevel level) {
    switch (level) {
        case LogLevel::Debug: return "DEBUG";
        case LogLevel::Info:  return "INFO";
        case LogLevel::Warn:  return "WARN";
        case LogLevel::Error: return "ERROR";
    }
    return "UNKNOWN";
}

void Logger::log(LogLevel level, const std::string& message, const std::source_location& loc) {
    auto now = std::chrono::system_clock::now();
    auto time = std::chrono::system_clock::to_time_t(now);

    std::cout << std::format(
        "{} | {} | {} | {}:{} | {}\n",
        std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S"),
        name_,
        level_to_string(level),
        loc.file_name(),
        loc.line(),
        message
    );
}

Logger& get_logger(const std::string& name) {
    std::lock_guard<std::mutex> lock(logger_mutex);
    auto [it, _] = loggers.try_emplace(name, name);
    return it->second;
}

} // namespace app::utils