VLink  2.3.0
A high-performance communication middleware
logger.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file logger.h
26  * @brief Singleton logger with stream / format / printf / RAII-stream entry points.
27  *
28  * @details
29  * @c vlink::Logger is the central logging facility. A single instance is constructed via
30  * @c Logger::init and reused for the rest of the process; each call routes through a console
31  * sink and an optional file sink whose minimum levels are independently configurable.
32  *
33  * @par Entry point cheat sheet
34  *
35  * | Style | Macro family | Backing API | Argument shape |
36  * | --------------- | --------------- | ----------------------------- | ------------------------------- |
37  * | Stream | @c VLOG_x | @c FastStream operator<< | @c VLOG_I("x=", x, " y=", y) |
38  * | Placeholder | @c MLOG_x | @c vlink::format::format_to_n | @c MLOG_W("x={} y={}", x, y) |
39  * | printf | @c CLOG_x | @c std::snprintf | @c CLOG_E("errno=%d", err) |
40  * | RAII stream | @c SLOG_x | @c WrapperStream | @c SLOG_D @c << "a=" @c << a |
41  *
42  * @par Severity ladder
43  *
44  * | Value | Name | Use case |
45  * | ----- | --------- | ----------------------------------------- |
46  * | 0 | @c kTrace | Verbose internals |
47  * | 1 | @c kDebug | Developer diagnostics |
48  * | 2 | @c kInfo | Normal operational messages |
49  * | 3 | @c kWarn | Unusual but recoverable conditions |
50  * | 4 | @c kError | Errors that may affect operation |
51  * | 5 | @c kFatal | Unrecoverable; throws @c RuntimeError |
52  * | 6 | @c kOff | Disables the corresponding sink |
53  *
54  * @par ASCII priority diagram
55  *
56  * @verbatim
57  * higher severity -> kFatal (throws)
58  * kError
59  * kWarn <- kDetailLevel (default): adds {file:line}
60  * kInfo
61  * kDebug
62  * kTrace
63  * lower severity -> kOff (sink disabled)
64  * @endverbatim
65  *
66  * @par Compile-time gating
67  * - @c VLINK_LOG_LEVEL @c =N strips levels below @c N at compile time (zero overhead).
68  * - @c VLINK_LOG_DETAIL_LEVEL @c =N changes the level at which file/line is appended.
69  * - @c VLINK_LOG_DISABLE_SHORT removes the @c VLOG_* / @c MLOG_* / @c CLOG_* / @c SLOG_* aliases.
70  *
71  * @par Runtime gating
72  * The four macro families test the active sink levels before evaluating their message arguments.
73  * Use @c VLINK_LOG_IF_x only when expensive preparation happens outside the macro arguments.
74  *
75  * @par Periodic call-site limiting
76  * @c VLOG_x_EVERY_MS(interval_ms, ...) emits immediately, then at most once per interval at that
77  * macro call site. The state is shared by concurrent callers, and suppressed log arguments are
78  * not evaluated. A non-positive interval bypasses limiting without updating the saved timestamp.
79  * Function-template specializations keep separate state. Fatal logs intentionally have no
80  * periodic variant.
81  *
82  * @par Formatting cheat sheet
83  *
84  * | Need | Snippet |
85  * | --------------------------------- | ------------------------------------------------------ |
86  * | Hex with 4 digits | @c VLOG_I(VLINK_LOG_HEX(4), value) |
87  * | Inline hex inside @c SLOG_* | @c SLOG_I @c << VLINK_LOG_HEXSS(4) @c << value |
88  * | Gate around expensive log args | @c if @c (VLINK_LOG_IF_D) @c { ... @c } |
89  *
90  * @par Example
91  * @code
92  * vlink::Logger::init("my_app", "/var/log/my_app");
93  * vlink::Logger::set_console_level(vlink::Logger::kInfo);
94  *
95  * VLOG_I("node started, id=", node_id);
96  * MLOG_W("temperature is {} C", temp);
97  * CLOG_E("errno=%d", errno);
98  * SLOG_D << "values: " << a << " " << b;
99  * @endcode
100  *
101  * @note @c kFatal messages call @c Logger::flush and then throw @c Exception::RuntimeError so
102  * the application can perform a controlled shutdown. Build-time backends include
103  * @c LoggerBackend, Android logcat, QNX slog2 and kmsg.
104  */
105 
106 #pragma once
107 
108 #include <atomic>
109 #include <cstdint>
110 #include <cstdio>
111 #include <iomanip>
112 #include <iostream>
113 #include <memory>
114 #include <string>
115 #include <string_view>
116 #include <type_traits>
117 #include <utility>
118 
119 #include "./exception.h"
120 #include "./fast_stream.h"
121 #include "./format.h"
122 #include "./functional.h"
123 #include "./macros.h"
124 
125 namespace vlink {
126 
127 /**
128  * @class Logger
129  * @brief Global singleton logger with four formatting styles and independently configurable sinks.
130  *
131  * @details
132  * Configure exactly once via @c Logger::init before the first @c get or logging call. Calls after
133  * singleton construction do not rebuild the active backend and must not be used for reconfiguration.
134  * Console and file output are independently enabled by their level thresholds; an empty
135  * @c log_path selects the configured or temporary default directory. Logging entry points are
136  * macros that wrap the public @c print_* templates and forward a compile-time @c Level so the
137  * bodies disappear when the level is below @c kMinimumLevel.
138  */
139 class VLINK_EXPORT Logger final {
140  public:
141  /**
142  * @brief Internal output style tag used by the @c print_* family.
143  *
144  * @details
145  * Callers normally interact with styles via macros; the enum is exposed for completeness.
146  */
147  enum Style : uint8_t {
148  kStreamStyle = 0, ///< Stream composition via @c FastStream operator<<.
149  kFormatStyle = 1, ///< Brace placeholders via @c vlink::format.
150  kCStyle = 2, ///< printf-style formatting via @c std::snprintf.
151  };
152 
153  /**
154  * @brief Message severity level.
155  *
156  * @details
157  * Lower numerical values are less severe. @c kOff is a sentinel that disables a sink.
158  */
159  enum Level : uint8_t {
160  kTrace = 0, ///< Verbose tracing.
161  kDebug = 1, ///< Developer diagnostics.
162  kInfo = 2, ///< Normal operational message.
163  kWarn = 3, ///< Recoverable but unusual condition.
164  kError = 4, ///< Recoverable error.
165  kFatal = 5, ///< Unrecoverable; throws @c Exception::RuntimeError.
166  kOff = 6, ///< Disable sink.
167  };
168 
169  /**
170  * @brief Compile-time minimum severity level; messages below this are stripped.
171  *
172  * @details
173  * Override by defining @c VLINK_LOG_LEVEL before including this header. Defaults to
174  * @c kTrace so every level is emitted by default.
175  */
176 #ifdef VLINK_LOG_LEVEL
177  static constexpr uint8_t kMinimumLevel = VLINK_LOG_LEVEL;
178 #else
179  static constexpr uint8_t kMinimumLevel = kTrace;
180 #endif
181 
182  /**
183  * @brief Severity threshold at and above which @c {file:line} is prepended to messages.
184  *
185  * @details
186  * Override by defining @c VLINK_LOG_DETAIL_LEVEL before including this header. Defaults to
187  * @c kWarn.
188  */
189 #ifdef VLINK_LOG_DETAIL_LEVEL
190  static constexpr uint8_t kDetailLevel = VLINK_LOG_DETAIL_LEVEL;
191 #else
192  static constexpr uint8_t kDetailLevel = kWarn;
193 #endif
194 
195  /**
196  * @brief Size of each C-style format buffer in bytes.
197  *
198  * @details
199  * Messages longer than @c kLocalBufferSize @c - @c 1 characters are silently truncated.
200  */
201  static constexpr int kLocalBufferSize = 4096;
202 
203  /**
204  * @brief Signature for custom console / file sink callbacks.
205  *
206  * @details
207  * Invoked synchronously from the logging thread, or the backend worker during backtrace replay.
208  * The view is valid only for the call. Handlers must support concurrent invocation. A handler
209  * may replace or unregister itself; such a registration takes effect once that handler returns,
210  * while registrations from other threads wait for handlers in progress and release the
211  * previous handler afterwards. Exceptions are reported to standard error and do not escape
212  * the logging boundary. Nested ordinary logging on the same thread is suppressed before
213  * arguments are evaluated; Fatal still throws.
214  */
215  using Callback = MoveFunction<void(Level, std::string_view)>;
216 
217  /**
218  * @brief Carries the source file name and line number for the detail prefix.
219  *
220  * @details
221  * Built automatically by @c VLINK_LOG_GET_DETAIL when the message level reaches
222  * @c kDetailLevel.
223  */
224  using DetailInfo = std::pair<std::string_view, int>;
225 
226  /**
227  * @brief Sentinel type indicating no detail prefix is attached.
228  *
229  * @details
230  * Used to avoid capturing @c __FILE__ / @c __LINE__ for messages below @c kDetailLevel.
231  */
232  struct NoDetail final {};
233 
234  /**
235  * @brief Initialises the logger singleton.
236  *
237  * @details
238  * Must be invoked before @c get or any logging macro. Only values supplied before the file
239  * channel is initialised configure the backend; later calls do not rebuild active sinks. File
240  * output is controlled by the file level. An empty @p log_path selects @c VLINK_LOG_DIR or a temporary
241  * default directory followed by @c app_name; @c VLINK_LOG_PID_ENABLE=1 appends the PID so concurrent
242  * instances of one application never share a rotating file set. An explicit directory must be
243  * owned by one live process.
244  *
245  * @param app_name Application name embedded in log output. Default: empty (detect automatically).
246  * @param log_path Base directory for generated log files when @p app_name is non-empty.
247  * Default: empty (select automatically).
248  */
249  static void init(const std::string& app_name = "", const std::string& log_path = "") noexcept;
250 
251  /**
252  * @brief Returns the global logger instance.
253  *
254  * @return Reference to the singleton.
255  */
256  static Logger& get() noexcept;
257 
258  /**
259  * @brief Flushes stdout, stderr and the active built-in file backend or plugin.
260  *
261  * @details
262  * Useful before abnormal termination. Invoked automatically before a @c kFatal message
263  * throws. Custom handlers manage their own buffering and flushing.
264  *
265  * @warning Call during application runtime, before static object destruction begins.
266  */
267  static void flush() noexcept;
268 
269  /**
270  * @brief Installs a custom console sink callback replacing the built-in console writer.
271  *
272  * @param callback Handler called with @c (level, @c message_view) for each record.
273  */
274  static void register_console_handler(Callback&& callback) noexcept;
275 
276  /**
277  * @brief Installs a custom file sink callback replacing the built-in file writer.
278  *
279  * @param callback Handler called with @c (level, @c message_view) for each record.
280  */
281  static void register_file_handler(Callback&& callback) noexcept;
282 
283  /**
284  * @brief Sets the minimum severity for the console sink; pass @c kOff to mute it.
285  *
286  * @param level Minimum output level.
287  */
288  static void set_console_level(Level level) noexcept;
289 
290  /**
291  * @brief Sets the minimum severity for the file sink; pass @c kOff to mute it.
292  *
293  * @param level Minimum output level.
294  */
295  static void set_file_level(Level level) noexcept;
296 
297  /**
298  * @brief Enables or disables the extended prefix on the console sink.
299  *
300  * @details
301  * The extended prefix contains the timestamp, thread ID and severity. ANSI level colours are
302  * independent of this setting.
303  *
304  * @param enable @c true to prepend the extended fields, @c false to omit them.
305  */
306  static void set_console_fmt_enable(bool enable) noexcept;
307 
308  /**
309  * @brief Returns the current console sink severity threshold.
310  *
311  * @return Current level.
312  */
313  [[nodiscard]] static Level get_console_level() noexcept;
314 
315  /**
316  * @brief Returns the current file sink severity threshold.
317  *
318  * @return Current level.
319  */
320  [[nodiscard]] static Level get_file_level() noexcept;
321 
322  /**
323  * @brief Returns whether the extended console prefix is enabled.
324  *
325  * @return @c true when timestamp, thread ID and severity fields are prepended.
326  */
327  [[nodiscard]] static bool get_console_fmt_enable() noexcept;
328 
329  /**
330  * @brief Sets @c std::ios_base format flags applied to stream-style records.
331  *
332  * @param flags Stream format flags.
333  */
334  static void set_stream_flag(std::ios_base::fmtflags flags) noexcept;
335 
336  /**
337  * @brief Sets the floating-point precision for stream-style records.
338  *
339  * @param precision Precision passed to @c std::setprecision.
340  */
341  static void set_stream_precision(int precision) noexcept;
342 
343  /**
344  * @brief Sets the minimum field width for stream-style records.
345  *
346  * @param width Field width passed to @c std::setw.
347  */
348  static void set_stream_width(int width) noexcept;
349 
350  /**
351  * @brief Returns the stream format flags currently applied to stream-style records.
352  *
353  * @return Format flags.
354  */
355  [[nodiscard]] static std::ios_base::fmtflags get_stream_flag() noexcept;
356 
357  /**
358  * @brief Returns the floating-point precision used for stream-style records.
359  *
360  * @return Precision value.
361  */
362  [[nodiscard]] static int get_stream_precision() noexcept;
363 
364  /**
365  * @brief Returns the field width used for stream-style records.
366  *
367  * @return Width value.
368  */
369  [[nodiscard]] static int get_stream_width() noexcept;
370 
371  /**
372  * @brief Enables a file-backend ring buffer of the most recent @p size eligible records.
373  *
374  * @details
375  * Console output keeps its threshold and handler. The file backend keeps every record in the
376  * ring and additionally writes Warn or higher immediately. Calling again resets the ring to
377  * the supplied capacity.
378  *
379  * @param size Capacity of the backtrace ring buffer.
380  *
381  * @warning Call during application runtime, before static object destruction begins.
382  */
383  static void enable_backtrace(size_t size) noexcept;
384 
385  /**
386  * @brief Disables backtrace capture and discards the ring buffer.
387  *
388  * @warning Call during application runtime, before static object destruction begins.
389  */
390  static void disable_backtrace() noexcept;
391 
392  /**
393  * @brief Dumps a snapshot to the built-in file backend and configured console sink.
394  *
395  * @details
396  * Console replay obeys its current threshold and handler, including Off. Retained records
397  * remain available for console replay after a permanent file error.
398  *
399  * @warning Call during application runtime, before static object destruction begins.
400  */
401  static void dump_backtrace() noexcept;
402 
403  /**
404  * @brief Reports whether the logger backend is being initialised.
405  *
406  * @return @c true while backend initialisation is in progress.
407  */
408  [[nodiscard]] static bool is_busy() noexcept;
409 
410  /**
411  * @brief Reports whether a record at @p level would currently be emitted.
412  *
413  * @details
414  * Ordinary logging macros already use this gate before evaluating their arguments. Call it
415  * directly only to guard preparation performed outside a macro call.
416  *
417  * @param level Severity level under test.
418  * @return @c true when the logger is active and the level passes a sink threshold, or when
419  * @p level is @c kFatal.
420  */
421  [[nodiscard]] static bool is_writable(Level level) noexcept;
422 
423  /**
424  * @brief Attempts to acquire the current period for one limited log call site.
425  *
426  * @param level Severity from @c kTrace through @c kError; other values are rejected.
427  * @param interval_ms Minimum interval in milliseconds; non-positive values disable limiting.
428  * @param last_log_time_ns Per-call-site monotonic timestamp, initially @c 0.
429  * @return @c true when the level is writable and the current period is acquired.
430  */
431  [[nodiscard]] static bool try_acquire_periodic_log(Level level, int64_t interval_ms,
432  std::atomic<uint64_t>& last_log_time_ns) noexcept;
433 
434  /**
435  * @brief Strips a path down to its final filename component at compile time.
436  *
437  * @param path Source path, typically @c __FILE__.
438  * @return View covering the filename portion.
439  */
440  [[nodiscard]] static constexpr std::string_view extract_filename(std::string_view path) noexcept;
441 
442  /**
443  * @brief Stream-style entry point (used by @c VLOG_* / @c print).
444  *
445  * @details
446  * Returns immediately when @c should_log<LevelT>() is @c false. Otherwise streams @p args
447  * into a thread-local @c FastStream and hands the resulting view to the sinks.
448  *
449  * @tparam LevelT Compile-time severity.
450  * @tparam DetailT Either @c DetailInfo or @c NoDetail.
451  * @tparam ArgsT Stream argument types.
452  * @param detail Source location info or @c NoDetail{}.
453  * @param args Values to stream.
454  */
455  template <Level LevelT, typename DetailT, typename... ArgsT>
456  static void print_stream_style(DetailT&& detail, ArgsT&&... args);
457 
458  /**
459  * @brief Placeholder-style entry point (used by @c MLOG_*).
460  *
461  * @tparam LevelT Compile-time severity.
462  * @tparam DetailT Either @c DetailInfo or @c NoDetail.
463  * @tparam ArgsT Format argument types.
464  * @param detail Source location info or @c NoDetail{}.
465  * @param format Format string with @c {} placeholders.
466  * @param args Format arguments.
467  */
468  template <Level LevelT, typename DetailT, typename... ArgsT>
469  static void print_format_style(DetailT&& detail, format::format_string<ArgsT...> format, ArgsT&&... args);
470 
471  /**
472  * @brief printf-style entry point (used by @c CLOG_*).
473  *
474  * @tparam LevelT Compile-time severity.
475  * @tparam DetailT Either @c DetailInfo or @c NoDetail.
476  * @tparam FormatT Format string type, typically @c const @c char*.
477  * @tparam ArgsT printf argument types.
478  * @param detail Source location info or @c NoDetail{}.
479  * @param format printf-style format string.
480  * @param args printf arguments.
481  */
482  template <Logger::Level LevelT, typename DetailT, typename FormatT, typename... ArgsT>
483  static void print_c_style(DetailT&& detail, FormatT&& format, ArgsT&&... args);
484 
485  /**
486  * @brief Convenience stream-style entry point without source location.
487  *
488  * @tparam LevelT Compile-time severity.
489  * @tparam ArgsT Stream argument types.
490  * @param args Values to stream.
491  */
492  template <Level LevelT, typename... ArgsT>
493  static void print(ArgsT&&... args);
494 
495  private:
496  struct StreamGuard final {
497  StreamGuard() noexcept = default;
498 
499  StreamGuard(StreamGuard&& other) noexcept : ptr(std::exchange(other.ptr, nullptr)) {}
500 
501  ~StreamGuard() noexcept {
502  if (ptr) {
503  release_local_stream(ptr);
504  }
505  }
506 
507  void acquire() noexcept { ptr = &get_local_stream(); }
508 
509  FastStream* ptr{nullptr};
510 
511  VLINK_DISALLOW_COPY_AND_ASSIGN(StreamGuard)
512  };
513 
514  public:
515  /**
516  * @struct WrapperStream
517  * @brief RAII helper backing @c SLOG_*; collects tokens and flushes on destruction.
518  *
519  * @details
520  * When @c kIsEnabled is @c false at the chosen level the type and its methods compile to
521  * nothing, so disabled-level call sites have zero runtime overhead.
522  *
523  * @tparam LevelT Compile-time severity level.
524  */
525  template <Logger::Level LevelT>
526  struct WrapperStream final {
527  static constexpr bool kIsEnabled = (LevelT >= kMinimumLevel && LevelT < Logger::kOff);
528 
529  explicit WrapperStream(Logger::NoDetail) noexcept {
530  if constexpr (kIsEnabled) {
531  if VLIKELY (should_log<LevelT>()) {
532  stream_.acquire();
533  }
534  }
535  }
536 
537  explicit WrapperStream(DetailInfo&& detail) noexcept {
538  if constexpr (kIsEnabled) {
539  if VLIKELY (should_log<LevelT>()) {
540  stream_.acquire();
541 
542  push_detail_to_stream(detail, *stream_.ptr);
543  }
544  }
545  }
546 
547  WrapperStream(WrapperStream&& other) noexcept = default;
548 
550 
551  ~WrapperStream() noexcept(LevelT != Level::kFatal) {
552  if constexpr (kIsEnabled) {
553  if VLIKELY (stream_.ptr) {
554  finalize_log<LevelT>(stream_.ptr->take_view());
555  }
556  }
557  }
558 
559  template <typename T>
560  WrapperStream& operator<<(T&& t) noexcept {
561  if constexpr (kIsEnabled) {
562  if VLIKELY (stream_.ptr) {
563  stream_.ptr->push(std::forward<T>(t));
564  }
565  }
566 
567  return *this;
568  }
569 
570  /**
571  * @brief Reports whether this stream accepted the record.
572  *
573  * @return @c true when the runtime level gate passed.
574  */
575  explicit operator bool() const noexcept { return stream_.ptr != nullptr; }
576 
577  private:
579 
580  StreamGuard stream_;
581  };
582 
583  private:
584  Logger() noexcept;
585 
586  ~Logger() noexcept;
587 
588  template <Level LevelT>
589  static bool should_log() noexcept;
590 
591  static bool can_log(Level level) noexcept;
592 
593  static void write(Level level, std::string_view log) noexcept;
594 
595  template <Level LevelT>
596  static void finalize_log(std::string_view log_view);
597 
598  template <typename DetailT>
599  static void push_detail_to_stream(DetailT&& detail, FastStream& stream) noexcept;
600 
601  template <typename DetailT>
602  static std::string_view format_with_detail(DetailT&& detail, const char* msg, int len, StreamGuard& guard) noexcept;
603 
604  static FastStream& get_local_stream() noexcept;
605 
606  static void release_local_stream(FastStream* stream) noexcept;
607 
608  void initialize_file_channel() noexcept;
609 
610  void initialize_plugin() noexcept;
611 
612  static void write_to_console(Level level, std::string_view log, bool formatted = false) noexcept;
613 
614  static void write_to_console_line(Level level, std::string_view log) noexcept;
615 
616  void write_to_file(Level level, std::string_view log) noexcept;
617 
618  struct Impl;
619  std::unique_ptr<Impl> impl_;
620 
621  template <Logger::Level LevelT>
622  friend struct WrapperStream;
623 
625 
627 };
628 
629 ////////////////////////////////////////////////////////////////
630 /// Details
631 ////////////////////////////////////////////////////////////////
632 
633 inline constexpr std::string_view Logger::extract_filename(std::string_view path) noexcept {
634  auto pos = path.find_last_of("/\\");
635  return (pos == std::string_view::npos) ? path : path.substr(pos + 1);
636 }
637 
638 template <Logger::Level LevelT, typename DetailT, typename... ArgsT>
639 inline void Logger::print_stream_style([[maybe_unused]] DetailT&& detail, [[maybe_unused]] ArgsT&&... args) {
640  if VUNLIKELY (!should_log<LevelT>()) {
641  return;
642  }
643 
644  StreamGuard guard;
645  guard.acquire();
646  auto& stream = *guard.ptr;
647 
648  if constexpr (std::is_same_v<std::decay_t<DetailT>, DetailInfo>) {
649  push_detail_to_stream(detail, stream);
650  }
651 
652  (stream.push(args), ...);
653 
654  finalize_log<LevelT>(stream.take_view());
655 }
656 
657 template <Logger::Level LevelT, typename DetailT, typename... ArgsT>
658 inline void Logger::print_format_style([[maybe_unused]] DetailT&& detail,
659  [[maybe_unused]] format::format_string<ArgsT...> format,
660  [[maybe_unused]] ArgsT&&... args) {
661  if VUNLIKELY (!should_log<LevelT>()) {
662  return;
663  }
664 
665  std::string_view log_view;
666 
667  StreamGuard guard;
668  char local_buffer[kLocalBufferSize];
669  auto result = format::format_to_n(local_buffer, kLocalBufferSize - 1, format, std::forward<ArgsT>(args)...);
670  auto written = static_cast<int>(result.out - local_buffer);
671 
672  local_buffer[written] = '\0';
673 
674  log_view = format_with_detail(detail, local_buffer, written, guard);
675 
676  finalize_log<LevelT>(log_view);
677 }
678 
679 template <Logger::Level LevelT, typename DetailT, typename FormatT, typename... ArgsT>
680 inline void Logger::print_c_style([[maybe_unused]] DetailT&& detail, [[maybe_unused]] FormatT&& format,
681  [[maybe_unused]] ArgsT&&... args) {
682  if VUNLIKELY (!should_log<LevelT>()) {
683  return;
684  }
685 
686  StreamGuard guard;
687 
688  if constexpr (sizeof...(ArgsT) == 0) {
689  guard.acquire();
690  auto& stream = *guard.ptr;
691 
692  if constexpr (std::is_same_v<std::decay_t<DetailT>, DetailInfo>) {
693  push_detail_to_stream(detail, stream);
694  }
695 
696  stream.push(format);
697  finalize_log<LevelT>(stream.take_view());
698  } else {
699  char local_buffer[kLocalBufferSize];
700  auto written = std::snprintf(local_buffer, kLocalBufferSize, format, args...);
701 
702  if VUNLIKELY (written < 0) {
703  written = 0;
704  } else if VUNLIKELY (written >= kLocalBufferSize) {
705  written = kLocalBufferSize - 1;
706  }
707 
708  finalize_log<LevelT>(format_with_detail(detail, local_buffer, written, guard));
709  }
710 }
711 
712 template <Logger::Level LevelT, typename... ArgsT>
713 inline void Logger::print([[maybe_unused]] ArgsT&&... args) {
714  print_stream_style<LevelT>(NoDetail{}, args...);
715 }
716 
717 template <Logger::Level LevelT>
718 inline bool Logger::should_log() noexcept {
719  if constexpr (LevelT < Logger::kMinimumLevel || LevelT >= Logger::kOff) {
720  return false;
721  } else if constexpr (LevelT == Logger::kFatal) {
722  return true;
723  } else {
724  return Logger::can_log(LevelT);
725  }
726 }
727 
728 template <Logger::Level LevelT>
729 inline void Logger::finalize_log(std::string_view log_view) {
730  Logger::write(LevelT, log_view);
731 
732  if constexpr (LevelT == Logger::kFatal) {
733  Logger::flush();
734  throw Exception::RuntimeError(std::string(log_view));
735  }
736 }
737 
738 template <typename DetailT>
739 inline void Logger::push_detail_to_stream(DetailT&& detail, FastStream& stream) noexcept {
740  auto& [file, line] = detail;
741  stream.push("{");
742  stream.push(file);
743  stream.push(":");
744  stream.push(line);
745  stream.push("} ");
746 }
747 
748 template <typename DetailT>
749 inline std::string_view Logger::format_with_detail(DetailT&& detail, const char* msg, int len,
750  StreamGuard& guard) noexcept {
751  if constexpr (std::is_same_v<std::decay_t<DetailT>, Logger::DetailInfo>) {
752  guard.acquire();
753  auto& stream = *guard.ptr;
754 
755  push_detail_to_stream(detail, stream);
756 
757  if VLIKELY (len > 0) {
758  stream.write_raw(msg, static_cast<size_t>(len));
759  }
760 
761  return stream.take_view();
762  } else {
763  if VLIKELY (len > 0) {
764  return std::string_view(msg, static_cast<size_t>(len));
765  }
766 
767  return {};
768  }
769 }
770 
771 } // namespace vlink
772 
774 
775 ////////////////////////////////////////////////////////////////
776 /// Macro Definitions
777 ////////////////////////////////////////////////////////////////
778 
779 #define VLINK_LOG_GET_DETAIL(level) \
780  ([]() -> auto { \
781  if constexpr ((level) >= VLinkLogger::kDetailLevel) { \
782  return VLinkLogger::DetailInfo{VLinkLogger::extract_filename(__FILE__), __LINE__}; \
783  } else { \
784  return VLinkLogger::NoDetail{}; \
785  } \
786  })()
787 
788 #define VLINK_LOG_HEX(offset) std::hex, std::uppercase, std::setw(offset), std::setfill('0')
789 
790 #define VLINK_LOG_HEXSS(offset) std::hex << std::uppercase << std::setw(offset) << std::setfill('0')
791 
792 #define VLINK_LOG_IF_T VLinkLogger::is_writable(VLinkLogger::kTrace)
793 
794 #define VLINK_LOG_IF_D VLinkLogger::is_writable(VLinkLogger::kDebug)
795 
796 #define VLINK_LOG_IF_I VLinkLogger::is_writable(VLinkLogger::kInfo)
797 
798 #define VLINK_LOG_IF_W VLinkLogger::is_writable(VLinkLogger::kWarn)
799 
800 #define VLINK_LOG_IF_E VLinkLogger::is_writable(VLinkLogger::kError)
801 
802 #define VLINK_LOG_IF_F VLinkLogger::is_writable(VLinkLogger::kFatal)
803 
804 #define VLINK_LOG_IS_WRITABLE(level) \
805  ((level) >= VLinkLogger::kMinimumLevel && (level) < VLinkLogger::kOff && VLinkLogger::is_writable(level))
806 
807 #define VLINK_LOG_CALL(level, function, ...) \
808  (VLINK_LOG_IS_WRITABLE(level) ? VLinkLogger::function<level>(VLINK_LOG_GET_DETAIL(level), __VA_ARGS__) \
809  : static_cast<void>(0))
810 
811 #define VLINK_LOG_T(...) VLINK_LOG_CALL(VLinkLogger::kTrace, print_stream_style, __VA_ARGS__)
812 
813 #define VLINK_LOG_D(...) VLINK_LOG_CALL(VLinkLogger::kDebug, print_stream_style, __VA_ARGS__)
814 
815 #define VLINK_LOG_I(...) VLINK_LOG_CALL(VLinkLogger::kInfo, print_stream_style, __VA_ARGS__)
816 
817 #define VLINK_LOG_W(...) VLINK_LOG_CALL(VLinkLogger::kWarn, print_stream_style, __VA_ARGS__)
818 
819 #define VLINK_LOG_E(...) VLINK_LOG_CALL(VLinkLogger::kError, print_stream_style, __VA_ARGS__)
820 
821 #define VLINK_LOG_F(...) VLINK_LOG_CALL(VLinkLogger::kFatal, print_stream_style, __VA_ARGS__)
822 
823 #define VLINK_MLOG_T(...) VLINK_LOG_CALL(VLinkLogger::kTrace, print_format_style, __VA_ARGS__)
824 
825 #define VLINK_MLOG_D(...) VLINK_LOG_CALL(VLinkLogger::kDebug, print_format_style, __VA_ARGS__)
826 
827 #define VLINK_MLOG_I(...) VLINK_LOG_CALL(VLinkLogger::kInfo, print_format_style, __VA_ARGS__)
828 
829 #define VLINK_MLOG_W(...) VLINK_LOG_CALL(VLinkLogger::kWarn, print_format_style, __VA_ARGS__)
830 
831 #define VLINK_MLOG_E(...) VLINK_LOG_CALL(VLinkLogger::kError, print_format_style, __VA_ARGS__)
832 
833 #define VLINK_MLOG_F(...) VLINK_LOG_CALL(VLinkLogger::kFatal, print_format_style, __VA_ARGS__)
834 
835 #define VLINK_CLOG_T(...) VLINK_LOG_CALL(VLinkLogger::kTrace, print_c_style, __VA_ARGS__)
836 
837 #define VLINK_CLOG_D(...) VLINK_LOG_CALL(VLinkLogger::kDebug, print_c_style, __VA_ARGS__)
838 
839 #define VLINK_CLOG_I(...) VLINK_LOG_CALL(VLinkLogger::kInfo, print_c_style, __VA_ARGS__)
840 
841 #define VLINK_CLOG_W(...) VLINK_LOG_CALL(VLinkLogger::kWarn, print_c_style, __VA_ARGS__)
842 
843 #define VLINK_CLOG_E(...) VLINK_LOG_CALL(VLinkLogger::kError, print_c_style, __VA_ARGS__)
844 
845 #define VLINK_CLOG_F(...) VLINK_LOG_CALL(VLinkLogger::kFatal, print_c_style, __VA_ARGS__)
846 
847 #define VLINK_SLOG_IMPL(level) \
848  VLINK_LOG_IS_WRITABLE(level) && VLinkLogger::WrapperStream<level>(VLINK_LOG_GET_DETAIL(level))
849 
850 #define VLINK_SLOG_T VLINK_SLOG_IMPL(VLinkLogger::kTrace)
851 
852 #define VLINK_SLOG_D VLINK_SLOG_IMPL(VLinkLogger::kDebug)
853 
854 #define VLINK_SLOG_I VLINK_SLOG_IMPL(VLinkLogger::kInfo)
855 
856 #define VLINK_SLOG_W VLINK_SLOG_IMPL(VLinkLogger::kWarn)
857 
858 #define VLINK_SLOG_E VLINK_SLOG_IMPL(VLinkLogger::kError)
859 
860 #define VLINK_SLOG_F VLINK_SLOG_IMPL(VLinkLogger::kFatal)
861 
862 #define VLINK_LOG_EVERY_MS_IMPL(level, interval_ms, ...) \
863  do { \
864  if constexpr ((level) >= VLinkLogger::kMinimumLevel && (level) < VLinkLogger::kFatal) { \
865  if VUNLIKELY ([](int64_t vlink_interval_ms) noexcept { \
866  static std::atomic<uint64_t> vlink_last_log_time_ns{0}; \
867  return VLinkLogger::try_acquire_periodic_log(level, vlink_interval_ms, vlink_last_log_time_ns); \
868  }(static_cast<int64_t>(interval_ms))) { \
869  VLinkLogger::print_stream_style<level>(VLINK_LOG_GET_DETAIL(level), __VA_ARGS__); \
870  } \
871  } \
872  } while (false)
873 
874 #define VLINK_LOG_T_EVERY_MS(interval_ms, ...) VLINK_LOG_EVERY_MS_IMPL(VLinkLogger::kTrace, interval_ms, __VA_ARGS__)
875 
876 #define VLINK_LOG_D_EVERY_MS(interval_ms, ...) VLINK_LOG_EVERY_MS_IMPL(VLinkLogger::kDebug, interval_ms, __VA_ARGS__)
877 
878 #define VLINK_LOG_I_EVERY_MS(interval_ms, ...) VLINK_LOG_EVERY_MS_IMPL(VLinkLogger::kInfo, interval_ms, __VA_ARGS__)
879 
880 #define VLINK_LOG_W_EVERY_MS(interval_ms, ...) VLINK_LOG_EVERY_MS_IMPL(VLinkLogger::kWarn, interval_ms, __VA_ARGS__)
881 
882 #define VLINK_LOG_E_EVERY_MS(interval_ms, ...) VLINK_LOG_EVERY_MS_IMPL(VLinkLogger::kError, interval_ms, __VA_ARGS__)
883 
884 #ifndef VLINK_LOG_DISABLE_SHORT
885 
886 #define VLOG_T_EVERY_MS(interval_ms, ...) VLINK_LOG_T_EVERY_MS(interval_ms, __VA_ARGS__)
887 
888 #define VLOG_D_EVERY_MS(interval_ms, ...) VLINK_LOG_D_EVERY_MS(interval_ms, __VA_ARGS__)
889 
890 #define VLOG_I_EVERY_MS(interval_ms, ...) VLINK_LOG_I_EVERY_MS(interval_ms, __VA_ARGS__)
891 
892 #define VLOG_W_EVERY_MS(interval_ms, ...) VLINK_LOG_W_EVERY_MS(interval_ms, __VA_ARGS__)
893 
894 #define VLOG_E_EVERY_MS(interval_ms, ...) VLINK_LOG_E_EVERY_MS(interval_ms, __VA_ARGS__)
895 
896 #define VLOG_T(...) VLINK_LOG_T(__VA_ARGS__)
897 
898 #define VLOG_D(...) VLINK_LOG_D(__VA_ARGS__)
899 
900 #define VLOG_I(...) VLINK_LOG_I(__VA_ARGS__)
901 
902 #define VLOG_W(...) VLINK_LOG_W(__VA_ARGS__)
903 
904 #define VLOG_E(...) VLINK_LOG_E(__VA_ARGS__)
905 
906 #define VLOG_F(...) VLINK_LOG_F(__VA_ARGS__)
907 
908 #define CLOG_T(...) VLINK_CLOG_T(__VA_ARGS__)
909 
910 #define CLOG_D(...) VLINK_CLOG_D(__VA_ARGS__)
911 
912 #define CLOG_I(...) VLINK_CLOG_I(__VA_ARGS__)
913 
914 #define CLOG_W(...) VLINK_CLOG_W(__VA_ARGS__)
915 
916 #define CLOG_E(...) VLINK_CLOG_E(__VA_ARGS__)
917 
918 #define CLOG_F(...) VLINK_CLOG_F(__VA_ARGS__)
919 
920 #define MLOG_T(...) VLINK_MLOG_T(__VA_ARGS__)
921 
922 #define MLOG_D(...) VLINK_MLOG_D(__VA_ARGS__)
923 
924 #define MLOG_I(...) VLINK_MLOG_I(__VA_ARGS__)
925 
926 #define MLOG_W(...) VLINK_MLOG_W(__VA_ARGS__)
927 
928 #define MLOG_E(...) VLINK_MLOG_E(__VA_ARGS__)
929 
930 #define MLOG_F(...) VLINK_MLOG_F(__VA_ARGS__)
931 
932 #define SLOG_T VLINK_SLOG_T
933 
934 #define SLOG_D VLINK_SLOG_D
935 
936 #define SLOG_I VLINK_SLOG_I
937 
938 #define SLOG_W VLINK_SLOG_W
939 
940 #define SLOG_E VLINK_SLOG_E
941 
942 #define SLOG_F VLINK_SLOG_F
943 
944 #endif
Thin final wrappers around the standard exception hierarchy used by VLink.
Allocation-light std::ostream backed by a growable string buffer.
Minimal heap-free {} placeholder formatter for the logger hot path.
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLINK_SINGLETON_CHECK(classname)
Embeds a static check that enforces one-instance-per-process for classname.
Definition: macros.h:192
#define VLINK_EXPORT
Definition: macros.h:81
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174