HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
log.hpp
1// Copyright Take Vos 2021-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "delayed_format.hpp"
8#include "format_check.hpp"
9#include "../container/container.hpp"
10#include "../time/time.hpp"
11#include "../utility/utility.hpp"
12#include "../concurrency/concurrency.hpp"
13#include "../char_maps/char_maps.hpp" // XXX #619
14#include "../macros.hpp"
15#include <chrono>
16#include <format>
17#include <string>
18#include <string_view>
19#include <tuple>
20#include <mutex>
21#include <atomic>
22#include <memory>
23#include <thread>
24#include <filesystem>
25#include <cstdio>
26
27hi_export_module(hikogui.telemetry : log);
28
29
30hi_export namespace hi { inline namespace v1 {
31namespace detail {
32
34public:
35 hi_force_inline log_message_base() noexcept = default;
36 virtual ~log_message_base() = default;
37
38 [[nodiscard]] virtual std::string format() const noexcept = 0;
39 [[nodiscard]] virtual std::unique_ptr<log_message_base> make_unique_copy() const noexcept = 0;
40};
41
42template<global_state_type Level, fixed_string SourcePath, int SourceLine, fixed_string Fmt, typename... Values>
44public:
45 static_assert(std::popcount(std::to_underlying(Level)) == 1);
46
47 // clang-format off
48 constexpr static char const *log_level_name =
49 Level == global_state_type::log_fatal ? "fatal" :
50 Level == global_state_type::log_error ? "error" :
51 Level == global_state_type::log_warning ? "warning" :
52 Level == global_state_type::log_info ? "info" :
53 Level == global_state_type::log_debug ? "debug" :
54 Level == global_state_type::log_trace ? "trace" :
55 Level == global_state_type::log_audit ? "audit" :
56 Level == global_state_type::log_statistics ? "stats" :
57 "<unknown log level>";
58 // clang-format on
59
60 log_message(log_message const&) noexcept = default;
61 log_message& operator=(log_message const&) noexcept = default;
62
63 template<typename... Args>
64 hi_force_inline log_message(Args&&...args) noexcept :
65 _time_stamp(time_stamp_count::inplace_with_thread_id{}), _what(std::forward<Args>(args)...)
66 {
67 }
68
69 std::string format() const noexcept override
70 {
71 auto const utc_time_point = time_stamp_utc::make(_time_stamp);
72 auto const sys_time_point = std::chrono::clock_cast<std::chrono::system_clock>(utc_time_point);
73 auto const local_time_point = cached_current_zone().to_local(sys_time_point);
74
75 auto const cpu_id = _time_stamp.cpu_id();
76 auto const thread_id = _time_stamp.thread_id();
77 auto const thread_name = get_thread_name(thread_id);
78
79 if constexpr (to_bool(Level & global_state_type::log_statistics)) {
80 return std::format("{} {}({}) {:5} {}", local_time_point, thread_name, cpu_id, log_level_name, _what());
81 } else {
82 auto source_filename = std::filesystem::path{static_cast<std::string_view>(SourcePath)}.filename().generic_string();
83 return std::format(
84 "{} {}({}) {:5} {} ({}:{})",
85 local_time_point,
86 thread_name,
87 cpu_id,
88 log_level_name,
89 _what(),
90 source_filename,
91 SourceLine);
92 }
93 }
94
95 [[nodiscard]] std::unique_ptr<log_message_base> make_unique_copy() const noexcept override
96 {
97 return std::make_unique<log_message>(*this);
98 }
99
100private:
101 time_stamp_count _time_stamp;
102 delayed_format<Fmt, Values...> _what;
103};
104
105} // namespace detail
106
107class log {
108public:
116 template<global_state_type Level, fixed_string SourcePath, int SourceLine, fixed_string Fmt, typename... Args>
117 hi_force_inline void add(Args&&...args) noexcept
118 {
119 static_assert(std::popcount(std::to_underlying(Level)) == 1);
120
121 auto const state = global_state.load(std::memory_order::relaxed);
122 if (not to_bool(state & Level)) {
123 return;
124 }
125
126 // Add messages in the queue, block when full.
127 // * This reduces amount of instructions needed to be executed during logging.
128 // * Simplifies logged_fatal_message logic.
129 // * Will make sure everything gets logged.
130 // * Blocking is bad in a real time thread, so maybe count the number of times it is blocked.
131
132 // Emplace a message directly on the queue.
134 std::forward<Args>(args)...);
135
136 if (to_bool(Level & global_state_type::log_fatal) or not to_bool(state & global_state_type::log_is_running)) [[unlikely]] {
137 // If the logger did not start we will log in degraded mode and log from the current thread.
138 // On fatal error we also want to log from the current thread.
139 flush();
140 }
141 }
142
147 hi_no_inline void flush() noexcept
148 {
149 bool wrote_message;
150 do {
152
153 {
154 auto const lock = std::scoped_lock(_mutex);
155
156 wrote_message = _fifo.take_one([&copy_of_message](auto& message) {
157 copy_of_message = message.make_unique_copy();
158 });
159 }
160
161 if (wrote_message) {
162 hi_assert_not_null(copy_of_message);
163 write(copy_of_message->format());
164 }
165 } while (wrote_message);
166 }
167
175 static bool start_subsystem(global_state_type log_level = global_state_type::log_level_default);
176
180 static void stop_subsystem()
181 {
182 return hi::stop_subsystem(log::subsystem_deinit);
183 }
184
185private:
188 wfree_fifo<detail::log_message_base, 64> _fifo;
189 mutable unfair_mutex _mutex;
190
195 void write(std::string const& str) const noexcept
196 {
197 std::println(stderr, "{}", str);
198 }
199
202 static inline std::jthread _log_thread;
203
208 static void log_thread_main(std::stop_token stop_token) noexcept;
209
212 static void subsystem_deinit() noexcept;
213
219 static bool subsystem_init() noexcept
220 {
221 _log_thread = std::jthread(log_thread_main);
222 return true;
223 }
224};
225
226inline log log_global;
227
229{
230 set_log_level(log_level);
231 if (hi::start_subsystem(global_state_type::log_is_running, log::subsystem_init, log::subsystem_deinit)) {
232 atterminate([]() {
233 log_global.flush();
234 });
235 return true;
236 } else {
237 return false;
238 }
239}
240
243inline void log::subsystem_deinit() noexcept
244{
245 if (global_state_disable(global_state_type::log_is_running)) {
246 if (_log_thread.joinable()) {
247 _log_thread.request_stop();
248 _log_thread.join();
249 }
250
251 log_global.flush();
252 }
253}
254
255}} // namespace hi::v1
std::string get_thread_name(thread_id id) noexcept
Get the thread name of a thread id.
Definition thread_intf.hpp:62
T::value_type start_subsystem(T &check_variable, typename T::value_type off_value, typename T::value_type(*init_function)(), void(*deinit_function)())
Start a sub-system.
Definition subsystem.hpp:117
std::atomic< global_state_type > global_state
The global state of the hikogui framework.
Definition global_state.hpp:203
bool global_state_disable(global_state_type subsystem, std::memory_order order=std::memory_order::seq_cst) noexcept
Disable a subsystem.
Definition global_state.hpp:249
global_state_type
The flag-type used for global state.
Definition global_state.hpp:32
void set_log_level(global_state_type log_level) noexcept
Set the logging level.
Definition global_state.hpp:232
void stop_subsystem(void(*deinit_function)())
Stop a sub-system.
Definition subsystem.hpp:203
@ write
Allow write access to a file.
The HikoGUI namespace.
Definition array_generic.hpp:20
void atterminate(std::function< void()> f) noexcept
Register functions that need to be called on std::terminate().
Definition terminate.hpp:48
cpu_id_result cpu_id(uint32_t leaf_id, uint32_t index=0) noexcept
A generic x86 cpu-id instruction.
Definition cpu_id_x86.hpp:347
std::chrono::time_zone const & cached_current_zone() noexcept
Cached current time zone.
Definition time_zone.hpp:39
DOXYGEN BUG.
Definition algorithm_misc.hpp:20
Definition log.hpp:43
Definition log.hpp:107
static bool start_subsystem(global_state_type log_level=global_state_type::log_level_default)
Start the logger system.
Definition log.hpp:228
hi_force_inline void add(Args &&...args) noexcept
Log a message.
Definition log.hpp:117
static void stop_subsystem()
Stop the logger system.
Definition log.hpp:180
hi_no_inline void flush() noexcept
Flush all messages from the log_queue directly from this thread.
Definition log.hpp:147
A string which may be used as a none-type template parameter.
Definition fixed_string.hpp:42
T log(T... args)