Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Log.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
14
15#include "Log.hpp"
16
17#include <algorithm>
18#include <charconv>
19#include <chrono>
20#include <cstdio>
21
22namespace esengine {
23
24std::atomic<LogLevel> Log::level_{LogLevel::Info};
25Log::Sinks Log::sinks_;
26std::mutex Log::sinks_mutex_;
27u32 Log::nextSinkId_ = 1;
28
29void Log::init() {
30#ifdef ES_DEBUG
31 level_ = LogLevel::Trace;
32#else
33 level_ = LogLevel::Info;
34#endif
35 info("ESEngine Log initialized");
36}
37
39 info("ESEngine Log shutdown");
40}
41
43 level_ = level;
44}
45
47 return level_;
48}
49
50const char* Log::levelToString(LogLevel level) {
51 switch (level) {
52 case LogLevel::Trace: return "TRACE";
53 case LogLevel::Debug: return "DEBUG";
54 case LogLevel::Info: return "INFO ";
55 case LogLevel::Warn: return "WARN ";
56 case LogLevel::Error: return "ERROR";
57 case LogLevel::Fatal: return "FATAL";
58 default: return "UNKNOWN";
59 }
60}
61
63 std::lock_guard lock(sinks_mutex_);
64 u32 id = nextSinkId_++;
65 sinks_.emplace_back(id, std::make_shared<LogSink>(std::move(sink)));
66 return id;
67}
68
69void Log::removeSink(u32 sinkId) {
70 std::lock_guard lock(sinks_mutex_);
71 sinks_.erase(
72 std::remove_if(sinks_.begin(), sinks_.end(),
73 [sinkId](const auto& pair) { return pair.first == sinkId; }),
74 sinks_.end());
75}
76
77void Log::emit(LogLevel level, const std::string& message) {
78 std::string line;
79 line.reserve(message.size() + 10);
80 line += '[';
81 line += levelToString(level);
82 line += "] ";
83 line += message;
84 line += '\n';
85 std::fputs(line.c_str(), level >= LogLevel::Error ? stderr : stdout);
86 notifySinks(level, message);
87}
88
89void Log::appendSigned(std::string& out, i64 value) {
90 char buf[24];
91 auto res = std::to_chars(buf, buf + sizeof buf, value);
92 out.append(buf, res.ptr);
93}
94
95void Log::appendUnsigned(std::string& out, u64 value) {
96 char buf[24];
97 auto res = std::to_chars(buf, buf + sizeof buf, value);
98 out.append(buf, res.ptr);
99}
100
101void Log::appendFloat(std::string& out, double value, int precision) {
102 char buf[400];
103 // What a stream prints by default is %g at six digits; "{:.Nf}" is %f at N.
104 int n = precision < 0 ? std::snprintf(buf, sizeof buf, "%g", value)
105 : std::snprintf(buf, sizeof buf, "%.*f", precision > 99 ? 99 : precision, value);
106 if (n > 0) out.append(buf, static_cast<usize>(n < static_cast<int>(sizeof buf) ? n : static_cast<int>(sizeof buf) - 1));
107}
108
109void Log::appendPointer(std::string& out, const void* value) {
110 char buf[32];
111 int n = std::snprintf(buf, sizeof buf, "%p", value);
112 if (n > 0) out.append(buf, static_cast<usize>(n));
113}
114
115int Log::precisionOf(const char* spec, const char* end) {
116 if (spec == end || spec[0] != ':' || end[-1] != 'f') return -1;
117 const char* dot = std::find(spec + 1, end, '.');
118 if (dot == end) return -1;
119 // Digits between '.' and the trailing 'f'. from_chars never throws; std::stoi would abort the whole module under -fno-exceptions on
120 // malformed specs like "{:.f}".
121 int precision = 0;
122 const char* begin = dot + 1;
123 auto res = std::from_chars(begin, end - 1, precision);
124 return res.ptr != begin ? precision : -1;
125}
126
127void Log::notifySinks(LogLevel level, const std::string& message) {
128 auto now = std::chrono::system_clock::now();
129 auto duration = now.time_since_epoch();
130 auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
131
132 LogEntry entry{level, message, static_cast<u64>(millis)};
133
134 Sinks snapshot;
135 {
136 std::lock_guard lock(sinks_mutex_);
137 snapshot = sinks_;
138 }
139 for (const auto& [id, sink] : snapshot) {
140 (*sink)(entry);
141 }
142}
143
144} // namespace esengine
Logging utilities for ESEngine.
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 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 LogLevel getLevel()
Gets the current minimum log level.
Definition Log.cpp:46
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
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