Zappy Server
C++ game server: world, rules, scheduler, network
Loading...
Searching...
No Matches
Logger.cpp
Go to the documentation of this file.
1#include "logging/Logger.hpp"
2
3#include <chrono>
4#include <cstdio>
5#include <ctime>
6
7static const char* _levelName(LogLevel level)
8{
9 switch (level) {
10 case LogLevel::Debug:
11 return "DEBUG";
12 case LogLevel::Info:
13 return "INFO";
14 case LogLevel::Warn:
15 return "WARN";
16 case LogLevel::Error:
17 return "ERROR";
18 }
19 return "?";
20}
21
22static std::string _timestamp()
23{
24 auto now = std::chrono::system_clock::now();
25 auto t = std::chrono::system_clock::to_time_t(now);
26 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
27
28 std::tm tm{};
29 localtime_r(&t, &tm);
30
31 char buf[32];
32 std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d.%03d", tm.tm_hour, tm.tm_min, tm.tm_sec,
33 static_cast<int>(ms.count()));
34 return buf;
35}
36
37Logger::Logger(LogLevel threshold) : _threshold(threshold) {}
38
39void Logger::setSink(std::unique_ptr<ILogSink> sink) { _sink = std::move(sink); }
40
41void Logger::_log(LogLevel level, std::string_view component, std::string_view msg)
42{
43 if (!_sink || level < _threshold) return;
44
45 std::string line = "[" + _timestamp() + "] [" + _levelName(level) + "] [" +
46 std::string(component) + "] " + std::string(msg);
47 _sink->write(level, line);
48}
49
50void Logger::debug(std::string_view component, std::string_view msg)
51{
52 _log(LogLevel::Debug, component, msg);
53}
54
55void Logger::info(std::string_view component, std::string_view msg)
56{
57 _log(LogLevel::Info, component, msg);
58}
59
60void Logger::warn(std::string_view component, std::string_view msg)
61{
62 _log(LogLevel::Warn, component, msg);
63}
64
65void Logger::error(std::string_view component, std::string_view msg)
66{
67 _log(LogLevel::Error, component, msg);
68}
LogLevel
Definition ILogSink.hpp:5
static const char * _levelName(LogLevel level)
Definition Logger.cpp:7
static std::string _timestamp()
Definition Logger.cpp:22
void info(std::string_view component, std::string_view msg)
Definition Logger.cpp:55
void debug(std::string_view component, std::string_view msg)
Definition Logger.cpp:50
void error(std::string_view component, std::string_view msg)
Definition Logger.cpp:65
void setSink(std::unique_ptr< ILogSink > sink)
Definition Logger.cpp:39
Logger(LogLevel threshold=LogLevel::Debug)
Definition Logger.cpp:37
void _log(LogLevel level, std::string_view component, std::string_view msg)
Definition Logger.cpp:41
std::unique_ptr< ILogSink > _sink
Definition Logger.hpp:32
LogLevel _threshold
Definition Logger.hpp:33
void warn(std::string_view component, std::string_view msg)
Definition Logger.cpp:60