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 "time_stamp_count.hpp"
8#include "time_stamp_utc.hpp"
9#include "wfree_fifo.hpp"
10#include "atomic.hpp"
11#include "meta.hpp"
12#include "source_location.hpp"
13#include "architecture.hpp"
14#include "delayed_format.hpp"
15#include "fixed_string.hpp"
16#include "subsystem.hpp"
17#include "global_state.hpp"
18#include "URL.hpp"
19#include "unfair_mutex.hpp"
20#include "debugger.hpp"
21#include "format_check.hpp"
22#include "thread.hpp"
23#include <chrono>
24#include <format>
25#include <string>
26#include <string_view>
27#include <tuple>
28#include <mutex>
29#include <atomic>
30#include <memory>
31#include <thread>
32#include <filesystem>
33
34namespace hi { inline namespace v1 {
35namespace detail {
36
38public:
39 hi_force_inline log_message_base() noexcept = default;
40 virtual ~log_message_base() = default;
41
42 [[nodiscard]] virtual std::string format() const noexcept = 0;
43 [[nodiscard]] virtual std::unique_ptr<log_message_base> make_unique_copy() const noexcept = 0;
44
45public:
46 static inline std::chrono::time_zone const *zone = nullptr;
47};
48
49template<global_state_type Level, fixed_string SourcePath, int SourceLine, fixed_string Fmt, typename... Values>
51public:
52 static_assert(std::popcount(to_underlying(Level)) == 1);
53
54 // clang-format off
55 static constexpr char const *log_level_name =
56 Level == global_state_type::log_fatal ? "fatal" :
57 Level == global_state_type::log_error ? "error" :
58 Level == global_state_type::log_warning ? "warning" :
59 Level == global_state_type::log_info ? "info" :
60 Level == global_state_type::log_debug ? "debug" :
61 Level == global_state_type::log_trace ? "trace" :
62 Level == global_state_type::log_audit ? "audit" :
63 Level == global_state_type::log_statistics ? "stats" :
64 "<unknown log level>";
65 // clang-format on
66
67 log_message(log_message const&) noexcept = default;
68 log_message& operator=(log_message const&) noexcept = default;
69
70 template<typename... Args>
71 hi_force_inline log_message(Args&&...args) noexcept :
72 _time_stamp(time_stamp_count::inplace_with_thread_id{}), _what(std::forward<Args>(args)...)
73 {
74 }
75
76 std::string format() const noexcept override
77 {
78 hilet utc_time_point = time_stamp_utc::make(_time_stamp);
79 hilet sys_time_point = std::chrono::clock_cast<std::chrono::system_clock>(utc_time_point);
80 hilet local_time_point = zone->to_local(sys_time_point);
81
82 hilet cpu_id = _time_stamp.cpu_id();
83 hilet thread_id = _time_stamp.thread_id();
84 hilet thread_name = get_thread_name(thread_id);
85
86 if constexpr (to_bool(Level & global_state_type::log_statistics)) {
87 return std::format("{} {}({}) {:5} {}\n", local_time_point, thread_name, cpu_id, log_level_name, _what());
88 } else {
89 auto source_filename = std::filesystem::path{static_cast<std::string_view>(SourcePath)}.filename().generic_string();
90 return std::format(
91 "{} {}({}) {:5} {} ({}:{})\n",
92 local_time_point,
93 thread_name,
94 cpu_id,
95 log_level_name,
96 _what(),
97 source_filename,
98 SourceLine);
99 }
100 }
101
102 [[nodiscard]] std::unique_ptr<log_message_base> make_unique_copy() const noexcept override
103 {
104 return std::make_unique<log_message>(*this);
105 }
106
107private:
108 time_stamp_count _time_stamp;
109 delayed_format<Fmt, Values...> _what;
110};
111
112} // namespace detail
113
114class log {
115public:
123 template<global_state_type Level, fixed_string SourcePath, int SourceLine, fixed_string Fmt, typename... Args>
124 hi_force_inline void add(Args&&...args) noexcept
125 {
126 static_assert(std::popcount(to_underlying(Level)) == 1);
127
128 hilet state = global_state.load(std::memory_order::relaxed);
129 if (not to_bool(state & Level)) {
130 return;
131 }
132
133 // Add messages in the queue, block when full.
134 // * This reduces amount of instructions needed to be executed during logging.
135 // * Simplifies logged_fatal_message logic.
136 // * Will make sure everything gets logged.
137 // * Blocking is bad in a real time thread, so maybe count the number of times it is blocked.
138
139 // Emplace a message directly on the queue.
141 std::forward<Args>(args)...);
142
143 if (to_bool(Level & global_state_type::log_fatal) or not to_bool(state & global_state_type::log_is_running)) {
144 // If the logger did not start we will log in degraded mode and log from the current thread.
145 // On fatal error we also want to log from the current thread.
146 [[unlikely]] flush();
147 }
148 }
149
154 hi_no_inline void flush() noexcept;
155
163 static bool start_subsystem(global_state_type log_level = global_state_type::log_level_default)
164 {
165 set_log_level(log_level);
166 return hi::start_subsystem(global_state_type::log_is_running, log::subsystem_init, log::subsystem_deinit);
167 }
168
172 static void stop_subsystem()
173 {
174 return hi::stop_subsystem(log::subsystem_deinit);
175 }
176
177private:
180 wfree_fifo<detail::log_message_base, 64> _fifo;
181 mutable unfair_mutex _mutex;
182
187 void write(std::string const& str) const noexcept;
188
191 static inline std::jthread _log_thread;
192
195 static void log_thread_main(std::stop_token stop_token) noexcept;
196
199 static void subsystem_deinit() noexcept;
200
206 static bool subsystem_init() noexcept;
207};
208
209inline log log_global;
210
213[[nodiscard]] std::string get_last_error_message() noexcept;
214
215}} // namespace hi::v1
216
217#define hi_log(level, fmt, ...) \
218 hi_format_check(fmt __VA_OPT__(, ) __VA_ARGS__); \
219 ::hi::log_global.add<level, __FILE__, __LINE__, fmt>(__VA_ARGS__)
220
221#define hi_log_debug(fmt, ...) hi_log(::hi::global_state_type::log_debug, fmt __VA_OPT__(, ) __VA_ARGS__)
222#define hi_log_info(fmt, ...) hi_log(::hi::global_state_type::log_info, fmt __VA_OPT__(, ) __VA_ARGS__)
223#define hi_log_statistics(fmt, ...) hi_log(::hi::global_state_type::log_statistics, fmt __VA_OPT__(, ) __VA_ARGS__)
224#define hi_log_trace(fmt, ...) hi_log(::hi::global_state_type::log_trace, fmt __VA_OPT__(, ) __VA_ARGS__)
225#define hi_log_audit(fmt, ...) hi_log(::hi::global_state_type::log_audit, fmt __VA_OPT__(, ) __VA_ARGS__)
226#define hi_log_warning(fmt, ...) hi_log(::hi::global_state_type::log_warning, fmt __VA_OPT__(, ) __VA_ARGS__)
227#define hi_log_error(fmt, ...) hi_log(::hi::global_state_type::log_error, fmt __VA_OPT__(, ) __VA_ARGS__)
228#define hi_log_fatal(fmt, ...) \
229 hi_log(::hi::global_state_type::log_fatal, fmt __VA_OPT__(, ) __VA_ARGS__); \
230 hi_debug_abort()
231
232#define hi_log_info_once(name, fmt, ...) \
233 do { \
234 if (++global_counter<name> == 1) { \
235 hi_log(::hi::global_state_type::log_info, fmt __VA_OPT__(, ) __VA_ARGS__); \
236 } \
237 } while (false)
238
239#define hi_log_error_once(name, fmt, ...) \
240 do { \
241 if (++global_counter<name> == 1) { \
242 hi_log(::hi::global_state_type::log_error, fmt __VA_OPT__(, ) __VA_ARGS__); \
243 } \
244 } while (false)
#define hilet
Invariant should be the default for variables.
Definition utility.hpp:23
Functions and macros for handling architectural difference between compilers, CPUs and operating syst...
STL namespace.
DOXYGEN BUG.
Definition algorithm.hpp:15
The HikoGUI namespace.
Definition ascii.hpp:19
std::string get_last_error_message() noexcept
Get the OS error message from the last error received on this thread.
Definition log.hpp:50
Definition log.hpp:114
static bool start_subsystem(global_state_type log_level=global_state_type::log_level_default)
Start the logger system.
Definition log.hpp:163
hi_force_inline void add(Args &&...args) noexcept
Log a message.
Definition log.hpp:124
static void stop_subsystem()
Stop the logger system.
Definition log.hpp:172
hi_no_inline void flush() noexcept
Flush all messages from the log_queue directly from this thread.