R-Type
Distributed multiplayer game engine in C++
Loading...
Searching...
No Matches
Logger.hpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2025
3** rtype
4** File description:
5** Logger - Centralized logging system with timestamps and file information
6*/
7
8#pragma once
9
10#include <chrono>
11#include <ctime>
12#include <iomanip>
13#include <iostream>
14#include <mutex>
15#include <sstream>
16#include <string>
17#include <string_view>
18
19namespace logger {
20
24 enum class Level {
25 DEBUG, // Detailed information for debugging
26 INFO, // General informational messages
27 WARNING, // Warning messages for potential issues
28 ERROR, // Error messages for failures
29 CRITICAL // Critical errors that may cause termination
30 };
31
35 namespace Colors {
36 constexpr const char *RESET = "\033[0m";
37 constexpr const char *LOG_GRAY = "\033[90m";
38 constexpr const char *LOG_GREEN = "\033[32m";
39 constexpr const char *LOG_YELLOW = "\033[33m";
40 constexpr const char *LOG_RED = "\033[31m";
41 constexpr const char *BOLD_RED = "\033[1;31m";
42 constexpr const char *CYAN = "\033[36m";
43 constexpr const char *BOLD_WHITE = "\033[1;37m";
44 } // namespace Colors
45
50 class Logger {
51 private:
52 static inline std::mutex _mutex;
53 static inline Level _minLevel = Level::DEBUG;
54 static inline bool _enableColors = true;
55
59 static std::string getBasename(const char *filePath) {
60 std::string path(filePath);
61 size_t pos = path.find_last_of("/\\");
62 return (pos == std::string::npos) ? path : path.substr(pos + 1);
63 }
64
68 static std::string getTimestamp() {
69 auto now = std::chrono::system_clock::now();
70 auto nowTime = std::chrono::system_clock::to_time_t(now);
71 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
72
73 std::tm timeInfo;
74#ifdef _WIN32
75 localtime_s(&timeInfo, &nowTime);
76#else
77 timeInfo = *std::localtime(&nowTime);
78#endif
79
80 std::ostringstream oss;
81 oss << std::put_time(&timeInfo, "%H:%M:%S");
82 oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
83 return oss.str();
84 }
85
89 static const char *getLevelColor(Level level) {
90 if (!_enableColors)
91 return "";
92
93 switch (level) {
94 case Level::DEBUG:
95 return Colors::LOG_GRAY;
96 case Level::INFO:
97 return Colors::LOG_GREEN;
98 case Level::WARNING:
99 return Colors::LOG_YELLOW;
100 case Level::ERROR:
101 return Colors::LOG_RED;
102 case Level::CRITICAL:
103 return Colors::BOLD_RED;
104 default:
105 return Colors::RESET;
106 }
107 }
108
112 static const char *getLevelString(Level level) {
113 switch (level) {
114 case Level::DEBUG:
115 return "DEBUG";
116 case Level::INFO:
117 return "INFO";
118 case Level::WARNING:
119 return "WARN";
120 case Level::ERROR:
121 return "ERROR";
122 case Level::CRITICAL:
123 return "CRIT";
124 default:
125 return "UNKNOWN";
126 }
127 }
128
129 public:
133 static void setLevel(Level level) { _minLevel = level; }
134
138 static void setColors(bool enable) { _enableColors = enable; }
139
143 static void log(Level level, const char *file, int line, const std::string &message) {
144 if (level < _minLevel)
145 return;
146
147 std::lock_guard<std::mutex> lock(_mutex);
148
149 const char *levelColor = getLevelColor(level);
150 const char *resetColor = _enableColors ? Colors::RESET : "";
151 const char *fileColor = _enableColors ? Colors::CYAN : "";
152 const char *timeColor = _enableColors ? Colors::BOLD_WHITE : "";
153
154 std::ostringstream oss;
155 oss << timeColor << "[" << getTimestamp() << "]" << resetColor << " ";
156 oss << levelColor << "[" << getLevelString(level) << "]" << resetColor << " ";
157 oss << fileColor << "[" << getBasename(file) << ":" << line << "]" << resetColor << " ";
158 oss << message;
159
160 std::cout << oss.str() << std::endl;
161 }
162
166 template <typename... Args>
167 static void logf(Level level, const char *file, int line, Args &&...args) {
168 if (level < _minLevel)
169 return;
170
171 std::ostringstream oss;
172 (oss << ... << std::forward<Args>(args));
173 log(level, file, line, oss.str());
174 }
175 };
176
177} // namespace logger
178
179// Convenience macros for logging
180#define LOG_DEBUG(...) logger::Logger::logf(logger::Level::DEBUG, __FILE__, __LINE__, __VA_ARGS__)
181#define LOG_INFO(...) logger::Logger::logf(logger::Level::INFO, __FILE__, __LINE__, __VA_ARGS__)
182#define LOG_WARNING(...) logger::Logger::logf(logger::Level::WARNING, __FILE__, __LINE__, __VA_ARGS__)
183#define LOG_ERROR(...) logger::Logger::logf(logger::Level::ERROR, __FILE__, __LINE__, __VA_ARGS__)
184#define LOG_CRITICAL(...) logger::Logger::logf(logger::Level::CRITICAL, __FILE__, __LINE__, __VA_ARGS__)
185
186// Short aliases
187#define LOG_D(...) LOG_DEBUG(__VA_ARGS__)
188#define LOG_I(...) LOG_INFO(__VA_ARGS__)
189#define LOG_W(...) LOG_WARNING(__VA_ARGS__)
190#define LOG_E(...) LOG_ERROR(__VA_ARGS__)
Thread-safe logging system with timestamps and source location.
Definition Logger.hpp:50
static std::mutex _mutex
Definition Logger.hpp:52
static std::string getTimestamp()
Get current timestamp with milliseconds.
Definition Logger.hpp:68
static void logf(Level level, const char *file, int line, Args &&...args)
Log a message with formatted arguments.
Definition Logger.hpp:167
static void setColors(bool enable)
Enable or disable colored output.
Definition Logger.hpp:138
static const char * getLevelString(Level level)
Get string representation of log level.
Definition Logger.hpp:112
static Level _minLevel
Definition Logger.hpp:53
static void log(Level level, const char *file, int line, const std::string &message)
Log a message with source location.
Definition Logger.hpp:143
static std::string getBasename(const char *filePath)
Extract basename from file path.
Definition Logger.hpp:59
static void setLevel(Level level)
Set minimum log level (messages below this level are ignored)
Definition Logger.hpp:133
static const char * getLevelColor(Level level)
Get color for log level.
Definition Logger.hpp:89
static bool _enableColors
Definition Logger.hpp:54
constexpr const char * CYAN
Definition Logger.hpp:42
constexpr const char * LOG_GRAY
Definition Logger.hpp:37
constexpr const char * LOG_RED
Definition Logger.hpp:40
constexpr const char * BOLD_RED
Definition Logger.hpp:41
constexpr const char * LOG_GREEN
Definition Logger.hpp:38
constexpr const char * RESET
Definition Logger.hpp:36
constexpr const char * BOLD_WHITE
Definition Logger.hpp:43
constexpr const char * LOG_YELLOW
Definition Logger.hpp:39
Level
Log severity levels.
Definition Logger.hpp:24