FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
log.hpp
Go to the documentation of this file.
1#pragma once
2// Asynchronous logging (5.10).
3//
4// FASTMM_LOG_INFO("filled {} @ {} on {}", qty, px, side);
5//
6// The call site captures a pointer to a static LogDescriptor (format string, file, line,
7// level) plus the packed argument values into a 256-byte LogRecord in the calling thread's
8// SpscRing. Nothing is formatted on the caller's thread; the LogSink thread pops records,
9// formats them with fmt and writes them to a FILE*. When a ring is full the record is
10// dropped and counted - the hot path never blocks.
11//
12// The format string is validated at compile time against the argument types (fmt), so a
13// mismatch is a compile error rather than a runtime surprise on the sink thread.
14//
15// Supported argument types: integers, floating point, bool, char, Price/Qty/Notional
16// (formatted as exact decimals), enums (via to_string() when available, else the
17// underlying integer), string_view / const char* / std::string / FixedString (copied,
18// truncated to kLogMaxStrBytes), Timestamp/Duration (ns as integers), Secret<T> ("***").
19#include "fastmm/core/config_macros.hpp"
20#include "fastmm/core/enums.hpp"
22#include "fastmm/core/fixed_string.hpp"
23#include "fastmm/core/spsc_ring.hpp"
25#include "fastmm/core/time.hpp"
26
27#include <fmt/base.h>
28
29#include <atomic>
30#include <concepts>
31#include <cstdint>
32#include <cstdio>
33#include <cstring>
34#include <string>
35#include <string_view>
36#include <type_traits>
37
38namespace fastmm {
39
40struct LogDescriptor {
41 const char* fmt;
42 const char* file;
43 std::uint32_t line;
45};
47enum class LogArgType : std::uint8_t {
48 Int = 1,
49 Uint = 2,
50 Double = 3,
51 Bool = 4,
52 Char = 5,
53 PriceFx = 6,
54 QtyFx = 7,
55 NotionalFx = 8,
56 Str = 9,
57 Secret = 10,
58};
59
60inline constexpr std::size_t kLogRecordBytes = 256;
61inline constexpr std::size_t kLogMaxStrBytes = 64;
62inline constexpr std::size_t kLogRingSize = 8192; // records per thread (2 MiB)
63inline constexpr std::size_t kLogMaxThreads = 64;
65struct LogRecord {
66 const LogDescriptor* desc;
67 std::int64_t ts_ns;
68 std::uint32_t tid;
69 std::uint32_t run; // LogRunScope: 1 + the run's index in its sweep, 0 outside one
70 std::uint8_t nargs;
71 std::uint8_t used;
72 std::uint8_t pad_[2];
73 std::uint8_t args[kLogRecordBytes - 28];
74};
75static_assert(sizeof(LogRecord) == kLogRecordBytes && std::is_trivially_copyable_v<LogRecord>);
76
77using LogRing = SpscRing<LogRecord, kLogRingSize>;
78
79// Wrap a value to have it rendered as "***".
80template <class T>
81struct Secret {
82 T value;
83};
84template <class T>
86 return Secret<std::decay_t<T>>{std::forward<T>(v)};
88
89// Global level (runtime); FASTMM_MIN_LOG_LEVEL is the compile-time floor.
90inline std::atomic<std::uint8_t> g_log_level{static_cast<std::uint8_t>(LogLevel::Info)};
91[[nodiscard]] FASTMM_FORCE_INLINE bool log_enabled(LogLevel lvl) noexcept {
92 return static_cast<std::uint8_t>(lvl) >= g_log_level.load(std::memory_order_relaxed);
94
95// Process-wide registry of per-thread rings + the sink thread. Implemented in log_sink.cpp.
96class Logger {
97 public:
98 static Logger& instance() noexcept;
99
100 void set_level(LogLevel lvl) noexcept { g_log_level.store(static_cast<std::uint8_t>(lvl)); }
101 [[nodiscard]] LogLevel level() const noexcept {
102 return static_cast<LogLevel>(g_log_level.load());
104
105 // Gives the calling thread a ring: a drained ring released by an exited thread if one exists,
106 // otherwise a new one (heap). Call during warm-up on every thread that logs; it is otherwise
107 // done lazily on the first log statement. Returns nullptr once kLogMaxThreads rings are in
108 // use at the same time.
110 // Returns the calling thread's ring to the pool. Runs automatically when a thread that logged
111 // exits, so short-lived threads (sweep workers, Python callers) never exhaust the slots.
112 void detach_current_thread() noexcept;
113 // Number of rings allocated so far; reused rings are not counted again.
114 [[nodiscard]] std::size_t thread_slots() const noexcept;
115
116 // Sink control. `out` defaults to stderr. Records at >= mirror_level are also copied to
117 // stderr when `out` is a different stream.
118 void start(std::FILE* out = stderr, LogLevel mirror_level = LogLevel::Warn);
119 // Opens `path` for appending and starts the sink on it. The logger owns this file: stop() closes
120 // it, and reopen() can swap it for a new one at the same path. False, and nothing started, when
121 // the file cannot be opened.
122 [[nodiscard]] bool start_file(const std::string& path, LogLevel mirror_level = LogLevel::Warn);
123 void stop(); // drains everything then joins the sink thread (and closes a start_file() file)
124 // Log rotation: the sink drains what was logged so far into the file it has open, then opens the
125 // path again, so a file renamed away (logrotate without copytruncate) is closed and the rest goes
126 // to a new one. request_reopen() only asks, and is async-signal-safe; reopen() waits for the
127 // sink. False: no start_file() file, or the path cannot be opened (the old file stays in use).
128 void request_reopen() noexcept;
129 [[nodiscard]] bool reopen();
130 // Drains all rings and fflush()es. Works with or without a running sink thread.
131 void flush();
132 [[nodiscard]] bool running() const noexcept { return running_.load(std::memory_order_acquire); }
133 // The sink writes to a stream other than stderr (a log file).
134 [[nodiscard]] bool to_file() const noexcept { return to_file_.load(std::memory_order_acquire); }
135
136 [[nodiscard]] std::uint64_t dropped() const noexcept {
137 return dropped_.load(std::memory_order_relaxed);
139 void note_drop() noexcept { dropped_.fetch_add(1, std::memory_order_relaxed); }
140 [[nodiscard]] std::uint64_t written() const noexcept {
141 return written_.load(std::memory_order_relaxed);
143
144 // Formats one record into `out` (appends). Public for tests/tools.
145 static void format_record(const LogRecord& r, std::string& out);
146
147 private:
148 Logger() = default;
149 ~Logger();
150 std::size_t drain_all(); // returns records processed
151 bool reopen_file(); // on the sink thread, or with no sink running
152 void sink_loop();
153
154 struct Impl;
155 Impl* impl_ = nullptr;
156 std::atomic<bool> running_{false};
157 std::atomic<bool> to_file_{false};
158 std::atomic<std::uint64_t> dropped_{0};
159 std::atomic<std::uint64_t> written_{0};
160};
161
162namespace detail {
163
164inline thread_local LogRing* t_log_ring = nullptr;
165inline thread_local std::uint32_t t_log_tid = 0;
166inline thread_local std::uint32_t t_log_slot = 0;
167inline thread_local bool t_log_thread_exiting = false; // set once thread-local teardown began
168inline thread_local const SimClock* t_log_clock = nullptr; // LogClockScope
169inline thread_local std::uint32_t t_log_run = 0; // LogRunScope
170
171// Compile-time floor check, written as a function so -Wtype-limits stays quiet when the
172// floor is 0.
173constexpr bool log_compiled(LogLevel l) noexcept {
174 const int v = static_cast<int>(l);
175 const int floor = FASTMM_MIN_LOG_LEVEL;
176 return v >= floor;
177}
178
179template <class E>
180concept EnumWithToString = std::is_enum_v<E> && requires(E e) {
181 { to_string(e) } -> std::convertible_to<std::string_view>;
182};
183template <class T>
184concept StringLike = std::convertible_to<const T&, std::string_view>;
185template <class T>
186struct IsSecret : std::false_type {};
187template <class T>
188struct IsSecret<Secret<T>> : std::true_type {};
189template <class T>
190struct IsFixed : std::false_type {};
191template <class Tag>
192struct IsFixed<Fixed<Tag>> : std::true_type {};
193
194// Type the sink hands to fmt for a given argument (used for compile-time format checks).
195template <class T>
196struct LogFmtTypeImpl {
197 using D = std::remove_cvref_t<T>;
198 using type = std::conditional_t<
199 std::is_same_v<D, bool>,
200 bool,
201 std::conditional_t<
202 std::is_same_v<D, char>,
203 char,
204 std::conditional_t<
205 std::is_integral_v<D>,
206 std::conditional_t<std::is_signed_v<D>, std::int64_t, std::uint64_t>,
207 std::conditional_t<
208 std::is_floating_point_v<D>,
209 double,
210 std::conditional_t<
211 IsFixed<D>::value || IsSecret<D>::value || StringLike<D> ||
212 EnumWithToString<D>,
213 std::string_view,
214 std::conditional_t<std::is_enum_v<D>,
215 std::int64_t,
216 std::conditional_t<std::is_same_v<D, Timestamp> ||
217 std::is_same_v<D, Duration>,
218 std::int64_t,
219 void>>>>>>>;
220 static_assert(!std::is_void_v<type>, "unsupported log argument type");
221};
222template <class T>
223using LogFmtType = typename LogFmtTypeImpl<T>::type;
224
225struct ArgPacker {
226 std::uint8_t* p;
227 std::uint8_t* end;
228 std::uint8_t n = 0;
229
230 FASTMM_FORCE_INLINE bool put_scalar(LogArgType t, std::uint64_t bits) noexcept {
231 if (end - p < 9) return false;
232 *p++ = static_cast<std::uint8_t>(t);
233 std::memcpy(p, &bits, 8);
234 p += 8;
235 ++n;
236 return true;
237 }
238 FASTMM_FORCE_INLINE bool put_str(LogArgType t, std::string_view s) noexcept {
239 const std::size_t room = static_cast<std::size_t>(end - p);
240 if (room < 2) return false;
241 std::size_t len = s.size() < kLogMaxStrBytes ? s.size() : kLogMaxStrBytes;
242 if (len > room - 2) len = room - 2;
243 *p++ = static_cast<std::uint8_t>(t);
244 *p++ = static_cast<std::uint8_t>(len);
245 if (len != 0) std::memcpy(p, s.data(), len); // an empty string_view may hold nullptr
246 if (len < s.size() && len >= 3) std::memcpy(p + len - 3, "...", 3); // make the cut visible
247 p += len;
248 ++n;
249 return true;
250 }
251};
252
253template <class T>
254FASTMM_FORCE_INLINE bool pack_arg(ArgPacker& pk, const T& v) noexcept {
255 using D = std::remove_cvref_t<T>;
256 if constexpr (std::is_same_v<D, bool>) {
257 return pk.put_scalar(LogArgType::Bool, v ? 1U : 0U);
258 } else if constexpr (std::is_same_v<D, char>) {
259 return pk.put_scalar(LogArgType::Char, static_cast<std::uint8_t>(v));
260 } else if constexpr (std::is_integral_v<D>) {
261 if constexpr (std::is_signed_v<D>) {
262 return pk.put_scalar(LogArgType::Int,
263 static_cast<std::uint64_t>(static_cast<std::int64_t>(v)));
264 } else {
265 return pk.put_scalar(LogArgType::Uint, static_cast<std::uint64_t>(v));
266 }
267 } else if constexpr (std::is_floating_point_v<D>) {
268 const double d = static_cast<double>(v);
269 std::uint64_t bits = 0;
270 std::memcpy(&bits, &d, 8);
271 return pk.put_scalar(LogArgType::Double, bits);
272 } else if constexpr (std::is_same_v<D, Price>) {
273 return pk.put_scalar(LogArgType::PriceFx, static_cast<std::uint64_t>(v.raw));
274 } else if constexpr (std::is_same_v<D, Qty>) {
275 return pk.put_scalar(LogArgType::QtyFx, static_cast<std::uint64_t>(v.raw));
276 } else if constexpr (std::is_same_v<D, Notional>) {
277 return pk.put_scalar(LogArgType::NotionalFx, static_cast<std::uint64_t>(v.raw));
278 } else if constexpr (IsSecret<D>::value) {
279 return pk.put_str(LogArgType::Secret, "***");
280 } else if constexpr (EnumWithToString<D>) {
281 return pk.put_str(LogArgType::Str, std::string_view(to_string(v)));
282 } else if constexpr (std::is_enum_v<D>) {
283 return pk.put_scalar(LogArgType::Int,
284 static_cast<std::uint64_t>(
285 static_cast<std::int64_t>(static_cast<std::underlying_type_t<D>>(v))));
286 } else if constexpr (std::is_same_v<D, Timestamp> || std::is_same_v<D, Duration>) {
287 return pk.put_scalar(LogArgType::Int, static_cast<std::uint64_t>(v.ns));
288 } else if constexpr (StringLike<D>) {
289 return pk.put_str(LogArgType::Str, std::string_view(v));
290 } else {
291 static_assert(sizeof(D) == 0, "unsupported log argument type");
292 return false;
293 }
294}
295
296template <class... Args>
297FASTMM_FORCE_INLINE void log_emit(const LogDescriptor& d, const Args&... args) noexcept {
298 LogRing* ring = t_log_ring;
299 if (FASTMM_UNLIKELY(ring == nullptr)) {
301 if (ring == nullptr) {
303 return;
304 }
305 }
306 LogRecord* r = ring->try_reserve();
307 if (FASTMM_UNLIKELY(r == nullptr)) {
309 return;
310 }
311 r->desc = &d;
312 r->ts_ns = t_log_clock != nullptr ? t_log_clock->now().ns : wall_now().ns;
313 r->tid = t_log_tid;
314 r->run = t_log_run;
315 ArgPacker pk{r->args, r->args + sizeof(r->args)};
316 (static_cast<void>(pack_arg(pk, args)), ...);
317 r->nargs = pk.n;
318 r->used = static_cast<std::uint8_t>(pk.p - r->args);
319 ring->commit();
320}
321
322} // namespace detail
323
324// While one is alive, the lines the thread logs carry the time of `clock` instead of the wall
325// clock: a backtest's and a replay's lines name the moment of the data they were written at.
326class LogClockScope {
327 public:
328 // Keeps the thread's clock, and restores it at the end (log_switch_run() changes it).
329 LogClockScope() noexcept : prev_(detail::t_log_clock) {}
330 explicit LogClockScope(const SimClock& clock) noexcept : prev_(detail::t_log_clock) {
331 detail::t_log_clock = &clock;
333 ~LogClockScope() { detail::t_log_clock = prev_; }
334 LogClockScope(const LogClockScope&) = delete;
337 private:
338 const SimClock* prev_;
339};
340
341// While one is alive, the lines the thread logs name run `index` of a sweep ("#index", the
342// points' order): a sweep's runs share the threads and the log.
343class LogRunScope {
344 public:
345 // Keeps the thread's run, and restores it at the end (log_switch_run() changes it).
346 LogRunScope() noexcept : prev_(detail::t_log_run) {}
347 explicit LogRunScope(std::size_t index) noexcept : prev_(detail::t_log_run) {
348 detail::t_log_run = static_cast<std::uint32_t>(index + 1);
350 ~LogRunScope() { detail::t_log_run = prev_; }
351 LogRunScope(const LogRunScope&) = delete;
354 private:
355 std::uint32_t prev_;
356};
357
358// Within a LogClockScope and a LogRunScope, the thread's lines from now on carry the time of
359// `clock` and name run `index` (a pass of a sweep switches between its runs).
360inline void log_switch_run(const SimClock& clock, std::size_t index) noexcept {
361 detail::t_log_clock = &clock;
362 detail::t_log_run = static_cast<std::uint32_t>(index + 1);
363}
364
365} // namespace fastmm
366
367// fmt_str must be a string literal. The generic lambda lets us spell the packed argument
368// types for the compile-time format check without touching the arguments' values.
369#define FASTMM_LOG_IMPL(lvl, fmt_str, ...) \
370 do { \
371 if constexpr (::fastmm::detail::log_compiled(lvl)) { \
372 if (::fastmm::log_enabled(lvl)) { \
373 static constexpr ::fastmm::LogDescriptor fastmm_log_desc_{ \
374 fmt_str, __FILE__, __LINE__, lvl}; \
375 [&](const auto&... fastmm_a_) { \
376 static_cast<void>( \
377 ::fmt::format_string<::fastmm::detail::LogFmtType<decltype(fastmm_a_)>...>( \
378 fmt_str)); \
379 ::fastmm::detail::log_emit(fastmm_log_desc_, fastmm_a_...); \
380 }(__VA_ARGS__); \
381 } \
382 } \
383 } while (0)
384
385#define FASTMM_LOG_TRACE(fmt_str, ...) \
386 FASTMM_LOG_IMPL(::fastmm::LogLevel::Trace, fmt_str __VA_OPT__(, ) __VA_ARGS__)
387#define FASTMM_LOG_DEBUG(fmt_str, ...) \
388 FASTMM_LOG_IMPL(::fastmm::LogLevel::Debug, fmt_str __VA_OPT__(, ) __VA_ARGS__)
389#define FASTMM_LOG_INFO(fmt_str, ...) \
390 FASTMM_LOG_IMPL(::fastmm::LogLevel::Info, fmt_str __VA_OPT__(, ) __VA_ARGS__)
391#define FASTMM_LOG_WARN(fmt_str, ...) \
392 FASTMM_LOG_IMPL(::fastmm::LogLevel::Warn, fmt_str __VA_OPT__(, ) __VA_ARGS__)
393#define FASTMM_LOG_ERROR(fmt_str, ...) \
394 FASTMM_LOG_IMPL(::fastmm::LogLevel::Error, fmt_str __VA_OPT__(, ) __VA_ARGS__)
While one is alive, the lines the thread logs carry the time of clock instead of the wall clock: a ba...
Definition log.hpp:328
LogClockScope() noexcept
Keeps the thread's clock, and restores it at the end (log_switch_run() changes it).
Definition log.hpp:331
~LogClockScope()
Definition log.hpp:335
LogClockScope & operator=(const LogClockScope &)=delete
While one is alive, the lines the thread logs name run index of a sweep ("\#index",...
Definition log.hpp:345
~LogRunScope()
Definition log.hpp:352
LogRunScope & operator=(const LogRunScope &)=delete
LogRunScope() noexcept
Keeps the thread's run, and restores it at the end (log_switch_run() changes it).
Definition log.hpp:348
Process-wide registry of per-thread rings + the sink thread. Implemented in log_sink....
Definition log.hpp:98
static Logger & instance() noexcept
LogLevel level() const noexcept
Definition log.hpp:103
std::size_t thread_slots() const noexcept
Number of rings allocated so far; reused rings are not counted again.
void start(std::FILE *out=stderr, LogLevel mirror_level=LogLevel::Warn)
Sink control.
bool start_file(const std::string &path, LogLevel mirror_level=LogLevel::Warn)
Opens path for appending and starts the sink on it.
void request_reopen() noexcept
Log rotation: the sink drains what was logged so far into the file it has open, then opens the path a...
void detach_current_thread() noexcept
Returns the calling thread's ring to the pool.
std::uint64_t written() const noexcept
Definition log.hpp:142
void stop()
drains everything then joins the sink thread (and closes a start_file() file)
std::uint64_t dropped() const noexcept
Definition log.hpp:138
void set_level(LogLevel lvl) noexcept
Definition log.hpp:102
void flush()
Drains all rings and fflush()es. Works with or without a running sink thread.
void note_drop() noexcept
Definition log.hpp:141
bool running() const noexcept
Definition log.hpp:134
LogRing * attach_current_thread()
Gives the calling thread a ring: a drained ring released by an exited thread if one exists,...
bool to_file() const noexcept
The sink writes to a stream other than stderr (a log file).
Definition log.hpp:136
static void format_record(const LogRecord &r, std::string &out)
Formats one record into out (appends). Public for tests/tools.
Deterministic clock for sim/backtest/replay. 1 cycle == 1 ns.
Definition time.hpp:338
Timestamp now() const noexcept
Definition time.hpp:342
All engine enumerations.
Fixed<Tag>: int64 fixed point with a global 1e-8 scale (ADR-0001).
Definition strategy.hpp:23
SpscRing< LogRecord, kLogRingSize > LogRing
Definition log.hpp:79
LogLevel
Definition enums.hpp:688
Secret< std::decay_t< T > > secret(T &&v)
Definition log.hpp:87
constexpr std::size_t kLogRecordBytes
Definition log.hpp:62
Timestamp wall_now() noexcept
CLOCK_REALTIME via vDSO (~20 ns). Implemented in src/core/time.cpp.
std::atomic< std::uint8_t > g_log_level
Global level (runtime); FASTMM_MIN_LOG_LEVEL is the compile-time floor.
Definition log.hpp:92
FASTMM_FORCE_INLINE bool log_enabled(LogLevel lvl) noexcept
Definition log.hpp:93
constexpr std::size_t kLogMaxStrBytes
Definition log.hpp:63
LogArgType
Definition log.hpp:49
constexpr std::size_t kLogRingSize
records per thread (2 MiB)
Definition log.hpp:64
constexpr std::string_view to_string(ParamType t) noexcept
Definition params.hpp:63
void log_switch_run(const SimClock &clock, std::size_t index) noexcept
Within a LogClockScope and a LogRunScope, the thread's lines from now on carry the time of clock and ...
Definition log.hpp:362
constexpr std::size_t kLogMaxThreads
Definition log.hpp:65
Strongly typed identifiers.
Definition log.hpp:42
LogLevel level
Definition log.hpp:46
const char * file
Definition log.hpp:44
const char * fmt
Definition log.hpp:43
std::uint32_t line
Definition log.hpp:45
Definition log.hpp:67
std::uint32_t run
LogRunScope: 1 + the run's index in its sweep, 0 outside one.
Definition log.hpp:71
std::uint8_t args[kLogRecordBytes - 28]
Definition log.hpp:75
std::int64_t ts_ns
Definition log.hpp:69
std::uint32_t tid
Definition log.hpp:70
std::uint8_t used
Definition log.hpp:73
std::uint8_t pad_[2]
Definition log.hpp:74
const LogDescriptor * desc
Definition log.hpp:68
std::uint8_t nargs
Definition log.hpp:72
Wrap a value to have it rendered as "***".
Definition log.hpp:83
T value
Definition log.hpp:84
std::int64_t ns
Definition time.hpp:46
Time primitives.