VLink  2.3.0
A high-performance communication middleware
logger_backend.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_backend.h
26  * @brief Asynchronous file backend used by @c vlink::Logger.
27  *
28  * @details
29  * The backend serialises file operations on a @c MessageLoop, periodically flushes through a
30  * loop-bound @c Timer, supports fixed-name and timestamped size rotation, and retains an optional
31  * backtrace ring. Applications normally use it when @c ENABLE_LOG_BACKEND is enabled; the class
32  * is also exposed for direct integration and focused backend testing.
33  */
34 
35 #pragma once
36 
37 #include <cstddef>
38 #include <cstdint>
39 #include <memory>
40 #include <string>
41 #include <string_view>
42 
43 #include "./functional.h"
44 #include "./logger.h"
45 #include "./message_loop.h"
46 
47 namespace vlink {
48 
49 /**
50  * @class LoggerBackend
51  * @brief MessageLoop-based asynchronous rotating-file backend.
52  *
53  * @details
54  * Each accepted record owns its message until a single worker thread formats and writes it.
55  * Queue overflow either blocks producers or discards an older record from the dispatcher queue
56  * according to @c Config::block_when_full; Error and Fatal records always block and remain
57  * protected. Low-frequency control operations use protected queue barriers, so @c flush and
58  * backtrace changes cannot be evicted by data-plane overflow.
59  *
60  * @note A backend must exclusively own its rotating-file set. Separate processes or backend
61  * instances should use separate paths. Flush transfers buffered bytes to the operating
62  * system but does not provide power-loss durability equivalent to @c fsync.
63  * @note Stop and join all callers before destruction. Inherited @c MessageLoop lifecycle
64  * controls may be used to stop the worker for diagnostics, but a stopped backend must not
65  * be restarted; direct shutdown may discard records that have not reached the worker batch.
66  */
67 class VLINK_EXPORT LoggerBackend final : public MessageLoop {
68  public:
69  /**
70  * @struct Config
71  * @brief Construction-time queue, file and formatting settings.
72  */
73  struct Config final {
74  std::string app_name; ///< Application name used by fixed-name rotation.
75  std::string log_path; ///< Base directory for generated log files.
76  size_t max_file_size{0}; ///< Rotation threshold in bytes; must be non-zero.
77  size_t max_files{0}; ///< Timestamp retention target, or fixed-name backups excluding the active file.
78  size_t queue_size{0}; ///< Dispatcher queue capacity; zero is clamped to one.
79  uint32_t flush_interval_ms{0}; ///< Periodic flush interval; zero flushes each record.
80  bool fixed_filename{false}; ///< Use @c <app>.log plus numeric backups when @c true.
81  bool append{false}; ///< Continue the active/latest file instead of starting a new file.
82  bool block_when_full{false}; ///< When true, block all producers; Error/Fatal are always protected.
83  bool use_utc{false}; ///< Format timestamps and filenames in UTC.
84  };
85 
86  /**
87  * @brief Callback invoked once when the backend enters a permanent error state.
88  *
89  * @details
90  * Receives the diagnostic message on the thread that detects the error. The message view is
91  * valid only during the callback. The callback must not destroy this backend or wait for its
92  * worker or invoke this backend; exceptions are isolated at the notification boundary.
93  */
94  using ErrorHandler = Function<void(std::string_view)>;
95 
96  /**
97  * @brief Callback used to emit preformatted backtrace records to a console sink.
98  *
99  * @details
100  * Receives the record level and one formatted line without its trailing newline. When stored
101  * by the constructor it receives Warn and higher records while backtrace capture is enabled;
102  * @c dump_backtrace may provide a callback for retained records. The line view is valid only
103  * during the callback, including nested writes. Logging and backtrace reconfiguration are allowed;
104  * recursive dumps and automatic console callbacks are suppressed. The callback must not destroy
105  * the backend or wait for its worker. Exceptions put the backend into its permanent error state.
106  */
107  using ConsoleWriter = Function<void(Logger::Level, std::string_view)>;
108 
109  /**
110  * @brief Constructs and starts the asynchronous backend.
111  *
112  * @param config Queue, file and formatting settings.
113  * @param error_handler Optional permanent-error notification.
114  * @param console_writer Optional backtrace console receiver.
115  *
116  * @note Backend initialisation failures enter the permanent error state and notify
117  * @p error_handler instead of throwing. Use @c has_error to inspect that state.
118  */
119  explicit LoggerBackend(Config&& config, ErrorHandler&& error_handler, ConsoleWriter&& console_writer = nullptr);
120 
121  /**
122  * @brief Drains records still pending at shutdown, flushes the file and stops the worker.
123  */
124  ~LoggerBackend() override;
125 
126  /**
127  * @brief Enqueues one record.
128  *
129  * @param level Record severity.
130  * @param message Message bytes copied into backend-owned storage.
131  * @return @c true when accepted for processing; @c false for @c kOff, after shutdown or
132  * permanent error, on allocation/enqueue failure, or when a non-blocking full queue
133  * contains no droppable record. Acceptance does not guarantee a later file write.
134  */
135  [[nodiscard]] bool log(Logger::Level level, std::string_view message) noexcept;
136 
137  /**
138  * @brief Drains non-evicted records preceding the barrier and flushes the active file.
139  */
140  void flush() noexcept;
141 
142  /**
143  * @brief Starts retaining the most recent records in a bounded ring.
144  *
145  * @param size Maximum retained record count.
146  */
147  void enable_backtrace(size_t size) noexcept;
148 
149  /**
150  * @brief Stops backtrace capture and discards retained records.
151  */
152  void disable_backtrace() noexcept;
153 
154  /**
155  * @brief Writes retained records to the file and optional console callback.
156  *
157  * @param console_writer Optional receiver for each preformatted line without its trailing newline.
158  * @note Callbacks may reconfigure the live ring; the dump consumes a snapshot. Recursive dumps
159  * and console callbacks are suppressed. Permanent file errors still permit console replay.
160  */
161  void dump_backtrace(const ConsoleWriter& console_writer) noexcept;
162 
163  /**
164  * @brief Reports whether the running backend entered a permanent error state.
165  *
166  * @return @c true after the first permanent backend error.
167  */
168  [[nodiscard]] bool has_error() const noexcept;
169 
170  /**
171  * @brief Returns the configured MessageLoop dispatcher queue capacity.
172  *
173  * @return Number of MessageLoop dispatcher queue slots, excluding the current worker batch.
174  */
175  [[nodiscard]] size_t get_max_task_count() const override;
176 
177  private:
178  struct LoggerRecord;
179 
180  struct Impl;
181 
182  void start_backend();
183 
184  void initialize_fixed();
185 
186  void initialize_timestamped();
187 
188  void open_current(bool append, bool report_error = true);
189 
190  void close_current() noexcept;
191 
192  void rotate_fixed();
193 
194  void rotate_timestamped();
195 
196  void flush_output();
197 
198  void write_output(std::string_view data);
199 
200  void update_timestamp(int64_t seconds);
201 
202  std::string_view format(const LoggerRecord& record);
203 
204  void fail(std::string_view message) noexcept;
205 
206  void flush_file() noexcept;
207 
208  void write(std::unique_ptr<LoggerRecord>&& record) noexcept;
209 
210  void barrier(Callback&& callback) noexcept;
211 
212  std::unique_ptr<Impl> impl_;
213 
215 };
216 
217 } // namespace vlink
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Singleton logger with stream / format / printf / RAII-stream entry points.
#define VLINK_EXPORT
Definition: macros.h:81
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174
Single-threaded task dispatcher with three queue backends, timers and scheduling envelopes.