Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Log.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
15#pragma once
16
17// =============================================================================
18// Includes
19// =============================================================================
20
21// Project includes
22#include "Types.hpp"
23
24// Standard library
25#include <atomic>
26#include <cstdlib>
27#include <functional>
28#include <memory>
29#include <mutex>
30#include <string>
31#include <string_view>
32#include <type_traits>
33#include <vector>
34
35namespace esengine {
36
37// =============================================================================
38// Log Level
39// =============================================================================
40
47enum class LogLevel : u8 {
48 Trace = 0,
49 Debug = 1,
50 Info = 2,
51 Warn = 3,
52 Error = 4,
53 Fatal = 5
54};
55
56struct LogEntry {
58 std::string message;
60};
61
62using LogSink = std::function<void(const LogEntry&)>;
63
64// =============================================================================
65// Log Class
66// =============================================================================
67
82class Log {
83public:
87 static void init();
88
92 static void shutdown();
93
98 static void setLevel(LogLevel level);
99
104 static LogLevel getLevel();
105
111 static u32 addSink(LogSink sink);
112
117 static void removeSink(u32 sinkId);
118
119 // =========================================================================
120 // Logging Methods
121 // =========================================================================
122
129 template<typename... Args>
130 static void trace(const char* fmt, Args&&... args) {
131 log(LogLevel::Trace, fmt, std::forward<Args>(args)...);
132 }
133
140 template<typename... Args>
141 static void debug(const char* fmt, Args&&... args) {
142 log(LogLevel::Debug, fmt, std::forward<Args>(args)...);
143 }
144
151 template<typename... Args>
152 static void info(const char* fmt, Args&&... args) {
153 log(LogLevel::Info, fmt, std::forward<Args>(args)...);
154 }
155
162 template<typename... Args>
163 static void warn(const char* fmt, Args&&... args) {
164 log(LogLevel::Warn, fmt, std::forward<Args>(args)...);
165 }
166
173 template<typename... Args>
174 static void error(const char* fmt, Args&&... args) {
175 log(LogLevel::Error, fmt, std::forward<Args>(args)...);
176 }
177
184 template<typename... Args>
185 static void fatal(const char* fmt, Args&&... args) {
186 log(LogLevel::Fatal, fmt, std::forward<Args>(args)...);
187 }
188
189private:
190 static std::atomic<LogLevel> level_;
191 using Sinks = std::vector<std::pair<u32, std::shared_ptr<LogSink>>>;
192 static Sinks sinks_;
193 static std::mutex sinks_mutex_;
194 static u32 nextSinkId_;
195
196 template<typename... Args>
197 static void log(LogLevel level, const char* fmt, Args&&... args) {
198 if (level < level_.load(std::memory_order_relaxed)) return;
199
200 std::string message;
201 formatTo(message, fmt, std::forward<Args>(args)...);
202 emit(level, message);
203 }
204
205 // Writes the line to stdout or stderr and hands it to the sinks. Not a template, and not a stream: a stream here pulled the whole of libc++'s
206 // iostream and locale machinery into every build for the sake of printing a line.
207 static void emit(LogLevel level, const std::string& message);
208 static void notifySinks(LogLevel level, const std::string& message);
209 static const char* levelToString(LogLevel level);
210
211 // The value formatters, kept out of the template so each argument type costs a call and not a copy of the formatting.
212 static void appendSigned(std::string& out, i64 value);
213 static void appendUnsigned(std::string& out, u64 value);
214 static void appendFloat(std::string& out, double value, int precision);
215 static void appendPointer(std::string& out, const void* value);
217 static int precisionOf(const char* spec, const char* end);
218
219 static void formatTo(std::string& out, const char* fmt) {
220 out += fmt;
221 }
222
223 template<typename T, typename... Args>
224 static void formatTo(std::string& out, const char* fmt, T&& value, Args&&... args) {
225 while (*fmt) {
226 if (*fmt == '{') {
227 const char* start = fmt + 1;
228 const char* end = start;
229 while (*end && *end != '}') ++end;
230
231 if (*end == '}') {
232 appendValue(out, value, precisionOf(start, end));
233 formatTo(out, end + 1, std::forward<Args>(args)...);
234 return;
235 }
236 }
237 out.push_back(*fmt++);
238 }
239 }
240
241 template<typename T>
242 static void appendValue(std::string& out, const T& value, int precision) {
243 using D = std::remove_cv_t<std::remove_reference_t<T>>;
244 if constexpr (std::is_same_v<D, bool>) {
245 out.push_back(value ? '1' : '0');
246 } else if constexpr (std::is_same_v<D, char> || std::is_same_v<D, signed char> || std::is_same_v<D, unsigned char>) {
247 out.push_back(static_cast<char>(value));
248 } else if constexpr (std::is_enum_v<D>) {
249 appendValue(out, static_cast<std::conditional_t<std::is_signed_v<std::underlying_type_t<D>>, i64, u64>>(value), precision);
250 } else if constexpr (std::is_integral_v<D>) {
251 if constexpr (std::is_signed_v<D>) appendSigned(out, static_cast<i64>(value));
252 else appendUnsigned(out, static_cast<u64>(value));
253 } else if constexpr (std::is_floating_point_v<D>) {
254 appendFloat(out, static_cast<double>(value), precision);
255 } else if constexpr (std::is_same_v<D, const char*> || std::is_same_v<D, char*>) {
256 if (value) out += value;
257 } else if constexpr (std::is_convertible_v<const D&, std::string_view>) {
258 out += std::string_view(value);
259 } else {
260 static_assert(std::is_pointer_v<D>, "Log cannot format this argument type");
261 appendPointer(out, static_cast<const void*>(value));
262 }
263 }
264};
265
266// =============================================================================
267// Logging Macros
268// =============================================================================
269
275#ifdef ES_DEBUG
277 #define ES_LOG_TRACE(...) ::esengine::Log::trace(__VA_ARGS__)
279 #define ES_LOG_DEBUG(...) ::esengine::Log::debug(__VA_ARGS__)
280#else
281 #define ES_LOG_TRACE(...) ((void)0)
282 #define ES_LOG_DEBUG(...) ((void)0)
283#endif
285
292#define ES_LOG_INFO(...) ::esengine::Log::info(__VA_ARGS__)
294#define ES_LOG_WARN(...) ::esengine::Log::warn(__VA_ARGS__)
296#define ES_LOG_ERROR(...) ::esengine::Log::error(__VA_ARGS__)
298#define ES_LOG_FATAL(...) ::esengine::Log::fatal(__VA_ARGS__)
300
301// =============================================================================
302// Assert Macro
303// =============================================================================
304
319#ifdef ES_DEBUG
320 #define ES_ASSERT(condition, message) \
321 do { \
322 if (!(condition)) { \
323 ES_LOG_FATAL("Assertion failed: {} at {}:{}", message, __FILE__, __LINE__); \
324 std::abort(); \
325 } \
326 } while (false)
327#else
328 #define ES_ASSERT(condition, message) ((void)0)
329#endif
330
331// =============================================================================
332// Verify Macro (always-on boundary guard)
333// =============================================================================
334
335namespace detail {
336
347using VerifyHook = void (*)(const char* cond, const char* file, int line);
348
350 static VerifyHook hook = nullptr;
351 return hook;
352}
353
354} // namespace detail
355
389#define ES_VERIFY(cond, ...) \
390 do { \
391 if (!(cond)) [[unlikely]] { \
392 ES_LOG_ERROR("Verify failed: ({}) at {}:{}", #cond, __FILE__, __LINE__); \
393 if (auto _es_vh = ::esengine::detail::verifyHook()) { \
394 _es_vh(#cond, __FILE__, __LINE__); \
395 } \
396 __VA_ARGS__; \
397 } \
398 } while (false)
399
413#define ES_VERIFY_FATAL(cond, message) \
414 do { \
415 if (!(cond)) [[unlikely]] { \
416 ES_LOG_FATAL("Fatal: {} ({}) at {}:{}", message, #cond, __FILE__, __LINE__); \
417 if (auto _es_vh = ::esengine::detail::verifyHook()) { \
418 _es_vh(#cond, __FILE__, __LINE__); \
419 } \
420 std::abort(); \
421 } \
422 } while (false)
423
424} // namespace esengine
Core type definitions and utilities for ESEngine.
Static logging interface.
Definition Log.hpp:82
static void trace(const char *fmt, Args &&... args)
Logs a trace message.
Definition Log.hpp:130
static void debug(const char *fmt, Args &&... args)
Logs a debug message.
Definition Log.hpp:141
static void info(const char *fmt, Args &&... args)
Logs an info message.
Definition Log.hpp:152
static void init()
Initializes the logging system.
Definition Log.cpp:29
static void warn(const char *fmt, Args &&... args)
Logs a warning message.
Definition Log.hpp:163
static void fatal(const char *fmt, Args &&... args)
Logs a fatal error message.
Definition Log.hpp:185
static void removeSink(u32 sinkId)
Unregisters a log sink.
Definition Log.cpp:69
static void shutdown()
Shuts down the logging system.
Definition Log.cpp:38
static u32 addSink(LogSink sink)
Registers a log sink to receive log entries.
Definition Log.cpp:62
static void setLevel(LogLevel level)
Sets the minimum log level.
Definition Log.cpp:42
static void error(const char *fmt, Args &&... args)
Logs an error message.
Definition Log.hpp:174
static LogLevel getLevel()
Gets the current minimum log level.
Definition Log.cpp:46
void(*)(const char *cond, const char *file, int line) VerifyHook
Optional sink invoked whenever an ES_VERIFY condition fails.
Definition Log.hpp:347
VerifyHook & verifyHook()
Definition Log.hpp:349
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
std::int64_t i64
Signed 64-bit integer.
Definition Types.hpp:56
std::function< void(const LogEntry &)> LogSink
Definition Log.hpp:62
LogLevel
Logging severity levels.
Definition Log.hpp:47
@ Info
General information.
Definition Log.hpp:50
@ Warn
Warning messages.
Definition Log.hpp:51
@ Fatal
Fatal errors (application cannot continue).
Definition Log.hpp:53
@ Error
Error messages.
Definition Log.hpp:52
@ Debug
Debug information.
Definition Log.hpp:49
@ Trace
Detailed debugging information.
Definition Log.hpp:48
auto sink(SignalType &signal)
Create a sink for a signal.
Definition Sink.hpp:175
std::string message
Definition Log.hpp:58
LogLevel level
Definition Log.hpp:57