Branch data Line data Source code
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 : : #include "./base/logger_backend.h"
25 : :
26 : : #include <algorithm>
27 : : #include <atomic>
28 : : #include <cerrno>
29 : : #include <charconv>
30 : : #include <chrono>
31 : : #include <cstdio>
32 : : #include <cstring>
33 : : #include <ctime>
34 : : #include <deque>
35 : : #include <exception>
36 : : #include <filesystem>
37 : : #include <limits>
38 : : #include <mutex>
39 : : #include <new>
40 : : #include <string>
41 : : #include <system_error>
42 : : #include <thread>
43 : : #include <utility>
44 : :
45 : : #include "./base/memory_pool.h"
46 : : #include "./base/memory_resource.h"
47 : : #include "./base/timer.h"
48 : : #include "./base/utils.h"
49 : :
50 : : #if defined(_WIN32)
51 : : #include <io.h>
52 : : #include <share.h>
53 : : #include <sys/stat.h>
54 : : #else
55 : : #include <sys/stat.h>
56 : : #include <unistd.h>
57 : : #endif
58 : :
59 : : namespace vlink {
60 : :
61 : : static constexpr size_t kMaxTimestampFiles = 10000U;
62 : : static constexpr size_t kMaxFixedFiles = 200000U;
63 : : static constexpr size_t kMaxPooledRecordSize = 512U;
64 : : static constexpr int kOpenRetryCount = 5;
65 : : static constexpr std::string_view kBacktraceStart = "****************** Backtrace Start ******************";
66 : : static constexpr std::string_view kBacktraceEnd = "****************** Backtrace End ********************";
67 : :
68 : : struct alignas(std::max_align_t) LoggerRecordHeader final {
69 : : size_t size{0U};
70 : : };
71 : :
72 : : struct LoggerBackend::LoggerRecord final {
73 : : LoggerRecord() = delete;
74 : :
75 : 23006 : LoggerRecord(Logger::Level record_level, std::chrono::system_clock::time_point record_timestamp,
76 : : uint64_t record_thread_id, std::string_view record_message) noexcept
77 : 23006 : : level(record_level),
78 : 23006 : timestamp(record_timestamp),
79 : 23006 : thread_id(record_thread_id),
80 : 23006 : message(reinterpret_cast<const char*>(this + 1), record_message.size()) {
81 [ + - ]: 23006 : if VLIKELY (!record_message.empty()) {
82 : 23006 : std::memcpy(const_cast<char*>(message.data()), record_message.data(), record_message.size());
83 : : }
84 : 23006 : }
85 : :
86 : : LoggerRecord(const LoggerRecord&) = delete;
87 : :
88 : : LoggerRecord& operator=(const LoggerRecord&) = delete;
89 : :
90 : 23006 : static void* operator new(size_t object_size, size_t message_size) noexcept {
91 : 23006 : constexpr size_t kHeaderSize = sizeof(LoggerRecordHeader);
92 : :
93 [ + - - + : 23006 : if VUNLIKELY (message_size > std::numeric_limits<size_t>::max() - object_size ||
- + ]
94 : : object_size + message_size > std::numeric_limits<size_t>::max() - kHeaderSize) {
95 : : return nullptr; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
96 : : }
97 : :
98 : 23007 : const size_t allocation_size = kHeaderSize + object_size + message_size;
99 : 23007 : const bool pooled = allocation_size <= kMaxPooledRecordSize;
100 : 23007 : std::byte* allocation = nullptr;
101 : :
102 : : try {
103 [ + + ]: 23007 : if VLIKELY (pooled) {
104 : : allocation = static_cast<std::byte*>(
105 [ + - ]: 23001 : MemoryPool::global_instance().allocate(allocation_size, alignof(LoggerRecordHeader)));
106 : : } else {
107 : 6 : allocation = static_cast<std::byte*>(::operator new(allocation_size, std::nothrow));
108 : : }
109 : 0 : } catch (...) {
110 : : return nullptr; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
111 : 0 : }
112 : :
113 [ - + ]: 23004 : if VUNLIKELY (allocation == nullptr) {
114 : : return nullptr; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
115 : : }
116 : :
117 : 23004 : auto* header = ::new (allocation) LoggerRecordHeader{allocation_size};
118 : :
119 : 23004 : return reinterpret_cast<std::byte*>(header) + kHeaderSize;
120 : : }
121 : :
122 : 23006 : static void operator delete(void* memory) noexcept {
123 : 23006 : auto* allocation = static_cast<std::byte*>(memory) - sizeof(LoggerRecordHeader);
124 : 23006 : auto* header = std::launder(reinterpret_cast<LoggerRecordHeader*>(allocation));
125 : 23006 : const size_t allocation_size = header->size;
126 : 23006 : header->~LoggerRecordHeader();
127 : :
128 [ + + ]: 23006 : if VLIKELY (allocation_size <= kMaxPooledRecordSize) {
129 : 23000 : MemoryPool::global_instance().deallocate(allocation, allocation_size, alignof(LoggerRecordHeader));
130 : : } else {
131 : 6 : ::operator delete(allocation);
132 : : }
133 : 23007 : }
134 : :
135 : : static void operator delete(void* memory, size_t) noexcept { // LCOV_EXCL_LINE GCOVR_EXCL_LINE
136 : : operator delete(memory); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
137 : : }
138 : :
139 : : Logger::Level level;
140 : : std::chrono::system_clock::time_point timestamp;
141 : : uint64_t thread_id;
142 : : std::string_view message;
143 : : };
144 : :
145 : : struct LoggerFileInfo final {
146 : : std::filesystem::path path;
147 : : std::string timestamp;
148 : : size_t index{0};
149 : : bool is_valid{false};
150 : : };
151 : :
152 : 14326 : static std::string_view get_backend_level_string(Logger::Level level) noexcept {
153 [ + - + + : 14326 : switch (level) {
+ + - # ]
154 : 1 : case Logger::kTrace:
155 : 1 : return "TRACE";
156 : 0 : case Logger::kDebug:
157 : 0 : return "DEBUG";
158 : 13687 : case Logger::kInfo:
159 : 13687 : return "INFO ";
160 : 296 : case Logger::kWarn:
161 : 296 : return "WARN ";
162 : 209 : case Logger::kError:
163 : 209 : return "ERROR";
164 : 134 : case Logger::kFatal:
165 : 134 : return "FATAL";
166 : : // LCOV_EXCL_START GCOVR_EXCL_START
167 : : case Logger::kOff:
168 : : return "EMPTY";
169 : : default:
170 : : return "EMPTY";
171 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
172 : : }
173 : : }
174 : :
175 : 103 : static std::filesystem::path fixed_file_path(const std::filesystem::path& path, size_t index) {
176 [ + + ]: 103 : if (index == 0U) {
177 [ + - ]: 28 : return path;
178 : : }
179 : :
180 [ + - ]: 75 : auto parent = path.parent_path();
181 [ + - ]: 75 : auto filename = path.stem();
182 [ + - ]: 75 : filename += ".";
183 [ + - + - ]: 75 : filename += std::to_string(index);
184 [ + - + - ]: 75 : filename += path.extension();
185 : :
186 [ + - ]: 75 : return parent / filename;
187 : 75 : }
188 : :
189 : 359 : static FILE* open_log_file_once(const std::filesystem::path& path, bool append, int& error_number) {
190 : : #if defined(_WIN32)
191 : : const wchar_t* mode = append ? L"ab" : L"wb";
192 : : FILE* file = ::_wfsopen(path.c_str(), mode, _SH_DENYWR);
193 : : error_number = file ? 0 : errno;
194 : :
195 : : return file;
196 : : #else
197 [ + + ]: 359 : FILE* file = std::fopen(path.c_str(), append ? "ab" : "wb");
198 [ - + ]: 359 : error_number = file ? 0 : errno;
199 : :
200 : 359 : return file;
201 : : #endif
202 : : }
203 : :
204 : 201 : static FILE* open_log_file(const std::filesystem::path& path, bool append, int& error_number) {
205 [ + - ]: 201 : for (int attempt = 0; attempt < kOpenRetryCount; ++attempt) {
206 [ + - ]: 201 : const auto parent = path.parent_path();
207 : :
208 [ + - ]: 201 : if (!parent.empty()) {
209 [ + + ]: 201 : std::filesystem::create_directories(parent);
210 : : }
211 : :
212 [ + + ]: 199 : if (!append) {
213 [ + - ]: 160 : FILE* truncate_file = open_log_file_once(path, false, error_number);
214 : :
215 : : // LCOV_EXCL_START GCOVR_EXCL_START
216 : : if (truncate_file && std::fclose(truncate_file) != 0) {
217 : : truncate_file = nullptr;
218 : : error_number = errno;
219 : : }
220 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
221 : :
222 [ - + ]: 160 : if (!truncate_file) {
223 [ # # ]: 0 : if (attempt + 1 < kOpenRetryCount) {
224 [ # # ]: 0 : std::this_thread::sleep_for(std::chrono::milliseconds(10));
225 : : }
226 : :
227 : 0 : continue;
228 : : }
229 : : }
230 : :
231 [ + - ]: 199 : FILE* file = open_log_file_once(path, true, error_number);
232 : :
233 [ + - ]: 199 : if (file) {
234 : 199 : return file;
235 : : }
236 : :
237 [ # # ]: 0 : if (attempt + 1 < kOpenRetryCount) {
238 [ # # ]: 0 : std::this_thread::sleep_for(std::chrono::milliseconds(10));
239 : : }
240 [ - - + ]: 201 : }
241 : :
242 : 0 : return nullptr;
243 : : }
244 : :
245 : 258 : static bool get_log_file_size(FILE* file, size_t& size, int& error_number) noexcept {
246 : : #if defined(_WIN32)
247 : : const int descriptor = ::_fileno(file);
248 : : struct _stat64 status{};
249 : :
250 : : if (descriptor < 0 || ::_fstat64(descriptor, &status) != 0 || status.st_size < 0) {
251 : : // LCOV_EXCL_START GCOVR_EXCL_START
252 : : error_number = errno;
253 : :
254 : : return false;
255 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
256 : : }
257 : : #else
258 : 258 : const int descriptor = ::fileno(file);
259 : 258 : struct stat status{};
260 : :
261 [ + - + - : 258 : if (descriptor < 0 || ::fstat(descriptor, &status) != 0 || status.st_size < 0) {
- + - + ]
262 : : // LCOV_EXCL_START GCOVR_EXCL_START
263 : : error_number = errno;
264 : :
265 : : return false;
266 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
267 : : }
268 : : #endif
269 : :
270 : 258 : const auto file_size = static_cast<uintmax_t>(status.st_size);
271 [ - + ]: 258 : size = file_size > std::numeric_limits<size_t>::max() ? std::numeric_limits<size_t>::max()
272 : : : static_cast<size_t>(file_size);
273 : 258 : error_number = 0;
274 : :
275 : 258 : return true;
276 : : }
277 : :
278 : 933 : static LoggerFileInfo parse_timestamp_file(const std::filesystem::path& path) {
279 : 933 : LoggerFileInfo info;
280 [ + - ]: 933 : info.path = path;
281 : :
282 [ + - + - ]: 933 : const auto stem = path.stem().string();
283 : :
284 [ - + ]: 933 : if (stem.size() < 21U) {
285 : 0 : return info;
286 : : }
287 : :
288 : 933 : const auto last_dot = stem.rfind('.');
289 : :
290 [ + - - + ]: 933 : if (last_dot == std::string::npos || last_dot != 19U) {
291 : 0 : return info;
292 : : }
293 : :
294 [ + - ]: 933 : info.timestamp.assign(stem, 0, last_dot);
295 : 933 : std::string_view index_string(stem.data() + last_dot + 1U, stem.size() - last_dot - 1U);
296 [ + - ]: 933 : auto [end, error] = std::from_chars(index_string.data(), index_string.data() + index_string.size(), info.index);
297 [ + - + - ]: 933 : info.is_valid = error == std::errc() && end == index_string.data() + index_string.size();
298 : :
299 : 933 : return info;
300 : 933 : }
301 : :
302 : : struct LoggerBackend::Impl final {
303 : : Config config;
304 : : ErrorHandler error_handler;
305 : : ConsoleWriter console_writer;
306 : :
307 : : std::filesystem::path base_path;
308 : : std::filesystem::path current_path;
309 : : size_t current_size{0};
310 : : size_t current_index{0};
311 : : FILE* file{nullptr};
312 : : #ifdef VLINK_ENABLE_BASE_MEMORY_RESOURCE
313 : : std::pmr::deque<LoggerFileInfo> timestamp_files{&MemoryResource::global_instance()};
314 : : #else
315 : : std::deque<LoggerFileInfo> timestamp_files;
316 : : #endif
317 : :
318 : : int64_t cached_seconds{std::numeric_limits<int64_t>::min()};
319 : : char timestamp_prefix[32]{};
320 : : size_t timestamp_size{0};
321 : : #ifdef VLINK_ENABLE_BASE_MEMORY_RESOURCE
322 : : std::pmr::string format_buffer{&MemoryResource::global_instance()};
323 : : #else
324 : : std::string format_buffer;
325 : : #endif
326 : :
327 : : decltype(format_buffer) console_buffer{format_buffer.get_allocator()};
328 : :
329 : : Timer flush_timer;
330 : : std::atomic_bool accepting{true};
331 : : std::atomic_bool has_error{false};
332 : : std::recursive_mutex stopped_mtx;
333 : :
334 : : bool backtrace_enabled{false};
335 : : bool dumping_backtrace{false};
336 : : bool invoking_console{false};
337 : : size_t backtrace_capacity{0};
338 : : #ifdef VLINK_ENABLE_BASE_MEMORY_RESOURCE
339 : : std::pmr::deque<std::unique_ptr<LoggerRecord>> backtrace{&MemoryResource::global_instance()};
340 : : #else
341 : : std::deque<std::unique_ptr<LoggerRecord>> backtrace;
342 : : #endif
343 : : };
344 : :
345 : 152 : LoggerBackend::LoggerBackend(Config&& config, ErrorHandler&& error_handler, ConsoleWriter&& console_writer)
346 [ + - ]: 152 : : impl_(std::make_unique<Impl>()) {
347 : 152 : impl_->error_handler = std::move(error_handler);
348 : 152 : impl_->console_writer = std::move(console_writer);
349 : : try {
350 [ + - ]: 152 : (void)MemoryPool::global_instance();
351 : :
352 : 152 : impl_->config = std::move(config);
353 : 152 : impl_->config.queue_size = std::max(impl_->config.queue_size, size_t{1});
354 [ + - ]: 152 : impl_->base_path = impl_->config.log_path;
355 [ + - ]: 152 : impl_->format_buffer.reserve(4096U);
356 [ + - ]: 152 : impl_->console_buffer.reserve(4096U);
357 : :
358 [ + + ]: 152 : if (impl_->config.flush_interval_ms > 0U) {
359 [ + - - + ]: 113 : if (!impl_->flush_timer.attach(this)) {
360 : : fail("logger backend: failed to attach flush timer"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
361 : : }
362 : :
363 [ + - ]: 113 : if (!impl_->has_error.load(std::memory_order_acquire)) {
364 [ + - ]: 113 : impl_->flush_timer.set_interval(impl_->config.flush_interval_ms);
365 [ + - ]: 113 : impl_->flush_timer.set_loop_count(Timer::kInfinite);
366 [ + - + - ]: 511 : impl_->flush_timer.set_callback([this] { flush_file(); });
367 : : }
368 : : }
369 : :
370 [ + - ]: 152 : if (!impl_->has_error.load(std::memory_order_acquire)) {
371 [ + + ]: 152 : start_backend();
372 : : }
373 [ + - ]: 2 : } catch (const std::exception& error) {
374 : 2 : fail(error.what());
375 : 2 : } catch (...) {
376 : 0 : fail("logger backend: failed to initialize");
377 [ - - ]: 0 : }
378 : :
379 [ + + ]: 152 : if (impl_->has_error.load(std::memory_order_acquire)) {
380 [ + - ]: 7 : impl_->flush_timer.stop();
381 : :
382 [ + - - + ]: 7 : if (is_running()) {
383 [ # # ]: 0 : quit();
384 [ # # ]: 0 : wait_for_quit(Timer::kInfinite, false);
385 : : }
386 : :
387 : 7 : close_current();
388 : : }
389 : 152 : }
390 : :
391 : 257 : LoggerBackend::~LoggerBackend() {
392 : 152 : impl_->accepting.store(false, std::memory_order_release);
393 : :
394 : : #ifdef _WIN32
395 : : if (Utils::is_terminating()) {
396 : : (void)impl_.release();
397 : : return;
398 : : }
399 : : #endif
400 : :
401 : 152 : impl_->flush_timer.stop();
402 : :
403 : : #ifdef _WIN32
404 : : (void)wait_for_quit(0, false);
405 : : #endif
406 : :
407 : 304 : barrier([this] { flush_file(); });
408 : :
409 : 152 : quit();
410 : 152 : wait_for_quit(Timer::kInfinite, false);
411 : :
412 : 152 : close_current();
413 : 257 : }
414 : :
415 : 23005 : bool LoggerBackend::log(Logger::Level level, std::string_view message) noexcept {
416 [ + + - + : 23005 : if VUNLIKELY (!impl_->accepting.load(std::memory_order_acquire) || impl_->has_error.load(std::memory_order_acquire) ||
+ + + + +
+ ]
417 : : level >= Logger::kOff) {
418 : 7 : return false;
419 : : }
420 : :
421 : : #ifdef _WIN32
422 : : if VUNLIKELY (Utils::is_terminating()) {
423 : : return false;
424 : : }
425 : : #endif
426 : :
427 : : try {
428 [ + + ]: 22998 : static thread_local const uint64_t kThreadId = Utils::get_native_thread_id();
429 : :
430 : : auto record = std::unique_ptr<LoggerRecord>(
431 [ + - ]: 22998 : new (message.size()) LoggerRecord(level, std::chrono::system_clock::now(), kThreadId, message));
432 : :
433 [ - + ]: 22997 : if VUNLIKELY (!record) {
434 : : fail("logger backend: failed to allocate a log record"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
435 : 0 : return false;
436 : : }
437 : :
438 [ + - + + ]: 22997 : if VUNLIKELY (is_in_same_thread()) {
439 : 22 : write(std::move(record));
440 : 22 : return !impl_->has_error.load(std::memory_order_acquire);
441 : : }
442 : :
443 : 22974 : bool protected_record = impl_->config.block_when_full;
444 : :
445 [ + + ]: 22974 : if VUNLIKELY (level >= Logger::kError) {
446 : 342 : protected_record = true;
447 : : }
448 : :
449 [ + + + + : 22974 : if VUNLIKELY (protected_record && !impl_->config.block_when_full) {
+ + ]
450 [ + - ]: 678 : Callback task = [this, record = std::move(record)]() mutable { write(std::move(record)); };
451 : :
452 [ + - + + ]: 339 : if VLIKELY (post_untracked_task(std::move(task), TaskOverflowPolicy::kUseDispatcherStrategy,
453 : : TaskDropPolicy::kProtected)) {
454 : 338 : return true;
455 : : }
456 : :
457 [ + - ]: 1 : return post_untracked_task(std::move(task), TaskOverflowPolicy::kBlock, TaskDropPolicy::kProtected);
458 : 339 : }
459 : :
460 [ + + + + : 67908 : return post_untracked_task(
+ - + - ]
461 : 36595 : [this, record = std::move(record)]() mutable { write(std::move(record)); },
462 : : protected_record ? TaskOverflowPolicy::kBlock : TaskOverflowPolicy::kUseDispatcherStrategy,
463 : 22637 : protected_record ? TaskDropPolicy::kProtected : TaskDropPolicy::kDroppable);
464 : : // LCOV_EXCL_START GCOVR_EXCL_START
465 : : } catch (const std::exception& error) {
466 : : fail(error.what());
467 : : return false;
468 : : } catch (...) {
469 : : fail("logger backend: failed to enqueue a log record");
470 : : return false;
471 : : }
472 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
473 : : }
474 : :
475 : 266 : void LoggerBackend::flush() noexcept {
476 : 532 : barrier([this] { flush_file(); });
477 : 266 : }
478 : :
479 : 11 : void LoggerBackend::enable_backtrace(size_t size) noexcept {
480 : 11 : barrier([this, size] {
481 : 11 : impl_->backtrace.clear();
482 : 11 : impl_->backtrace_capacity = size;
483 : 11 : impl_->backtrace_enabled = true;
484 : 11 : });
485 : 11 : }
486 : :
487 : 10 : void LoggerBackend::disable_backtrace() noexcept {
488 : 10 : barrier([this] {
489 : 10 : impl_->backtrace_enabled = false;
490 : 10 : impl_->backtrace_capacity = 0U;
491 : 10 : impl_->backtrace.clear();
492 : 10 : });
493 : 10 : }
494 : :
495 : 12 : void LoggerBackend::dump_backtrace(const ConsoleWriter& console_writer) noexcept {
496 : 12 : barrier([this, &console_writer] {
497 [ + + + - : 12 : if (impl_->dumping_backtrace || !impl_->backtrace_enabled || impl_->backtrace.empty()) {
+ + + + ]
498 : 7 : return;
499 : : }
500 : :
501 : 5 : impl_->dumping_backtrace = true;
502 : :
503 : : try {
504 [ + - ]: 5 : decltype(impl_->backtrace) records(impl_->backtrace.get_allocator());
505 : 5 : records.swap(impl_->backtrace);
506 : :
507 : 183 : auto dump_record = [this, &console_writer](const LoggerRecord& record) {
508 [ + - ]: 17 : const auto formatted = format(record);
509 : :
510 [ - + ]: 17 : if (formatted.empty()) {
511 : 0 : return;
512 : : }
513 : :
514 [ + + ]: 17 : if VLIKELY (!impl_->has_error.load(std::memory_order_relaxed)) {
515 [ + - ]: 13 : write_output(formatted);
516 : : }
517 : :
518 [ + - + - : 17 : if (console_writer && !impl_->invoking_console) {
+ - ]
519 : 17 : impl_->console_buffer.swap(impl_->format_buffer);
520 : 17 : impl_->invoking_console = true;
521 : :
522 : : try {
523 : 17 : const std::string_view console_log(impl_->console_buffer);
524 [ + - + + ]: 17 : console_writer(record.level, console_log.substr(0U, console_log.size() - 1U));
525 : 1 : } catch (...) {
526 : 1 : impl_->invoking_console = false;
527 : 1 : throw;
528 : 1 : }
529 : :
530 : 16 : impl_->invoking_console = false;
531 : : }
532 : 5 : };
533 : :
534 : 5 : const uint64_t thread_id = Utils::get_native_thread_id();
535 : :
536 : 9 : auto dump_marker = [&](std::string_view text) {
537 : : auto marker = std::unique_ptr<LoggerRecord>(
538 [ + - ]: 9 : new (text.size()) LoggerRecord(Logger::kInfo, std::chrono::system_clock::now(), thread_id, text));
539 : :
540 [ + - ]: 9 : if (marker) {
541 [ + + ]: 9 : dump_record(*marker);
542 : : } else {
543 : 0 : fail("logger backend: failed to allocate a log record");
544 : : }
545 : 9 : };
546 : :
547 [ + + ]: 5 : dump_marker(kBacktraceStart);
548 : :
549 [ + + ]: 12 : for (const auto& record : records) {
550 [ + - ]: 8 : dump_record(*record);
551 : : }
552 : :
553 [ + - ]: 4 : dump_marker(kBacktraceEnd);
554 : :
555 [ + + ]: 4 : if VLIKELY (!impl_->has_error.load(std::memory_order_relaxed)) {
556 [ + - ]: 3 : flush_output();
557 : : }
558 [ - + ]: 6 : } catch (const std::exception& error) {
559 : 0 : fail(error.what());
560 : 1 : } catch (...) {
561 : 1 : fail("logger backend: failed to dump backtrace");
562 : 1 : }
563 : :
564 : 5 : impl_->dumping_backtrace = false;
565 : : });
566 : 12 : }
567 : :
568 : 22 : bool LoggerBackend::has_error() const noexcept { return impl_->has_error.load(std::memory_order_acquire); }
569 : :
570 : 39455 : size_t LoggerBackend::get_max_task_count() const { return impl_->config.queue_size; }
571 : :
572 : 152 : void LoggerBackend::start_backend() {
573 [ + + ]: 152 : if (impl_->config.max_file_size == 0U) {
574 : 1 : fail("logger backend: max_file_size cannot be zero");
575 : 5 : return;
576 : : }
577 : :
578 [ + + ]: 151 : const size_t max_supported_files = impl_->config.fixed_filename ? kMaxFixedFiles : kMaxTimestampFiles;
579 : :
580 [ + + ]: 151 : if (impl_->config.max_files > max_supported_files) {
581 : 2 : fail("logger backend: max_files exceeds the supported limit");
582 : 2 : return;
583 : : }
584 : :
585 [ + + + + : 149 : if (!impl_->config.fixed_filename && impl_->config.max_files == 0U) {
+ + ]
586 : 1 : fail("logger backend: max_files cannot be zero for timestamp rotation");
587 : 1 : return;
588 : : }
589 : :
590 [ + + ]: 148 : if (impl_->config.fixed_filename) {
591 [ + + ]: 39 : initialize_fixed();
592 : : } else {
593 [ + - ]: 109 : initialize_timestamped();
594 : : }
595 : :
596 [ + + ]: 146 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
597 : 1 : return;
598 : : }
599 : :
600 [ + - + - ]: 145 : set_name("VLinkLogger");
601 [ + + + - ]: 145 : set_strategy(impl_->config.block_when_full ? MessageLoop::kBlockStrategy : MessageLoop::kPopStrategy);
602 : :
603 [ + - - + ]: 145 : if (!async_run()) {
604 : : fail("logger backend: failed to start message loop"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
605 : 0 : return;
606 : : }
607 : :
608 : 145 : PostTaskOptions options;
609 : 145 : options.overflow_policy = TaskOverflowPolicy::kBlock;
610 : 145 : options.drop_policy = TaskDropPolicy::kProtected;
611 : :
612 [ + - + - ]: 145 : auto handle = post_task_handle([] {}, options);
613 [ + - ]: 145 : (void)handle.wait();
614 : :
615 [ - + ]: 145 : if VUNLIKELY (handle.state() != TaskExecutionState::kCompleted) {
616 : : fail("logger backend: failed to start message loop"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
617 : 0 : return;
618 : : }
619 : :
620 [ + + ]: 145 : if (impl_->config.flush_interval_ms > 0U) {
621 [ + - ]: 112 : impl_->flush_timer.start();
622 : : }
623 [ + - + - ]: 145 : }
624 : :
625 : 39 : void LoggerBackend::initialize_fixed() {
626 [ + - ]: 39 : impl_->base_path /= impl_->config.app_name + ".log";
627 : 39 : impl_->current_path = impl_->base_path;
628 : :
629 : 39 : open_current(true);
630 : :
631 [ - + ]: 37 : if VUNLIKELY (impl_->has_error.load(std::memory_order_acquire)) {
632 : 0 : return;
633 : : }
634 : :
635 [ + + + + : 37 : if (!impl_->config.append && impl_->current_size > 0U) {
+ + ]
636 : 1 : rotate_fixed();
637 : : }
638 : : }
639 : :
640 : 109 : void LoggerBackend::initialize_timestamped() {
641 [ + + + + : 109 : if (std::filesystem::exists(impl_->base_path) && !std::filesystem::is_directory(impl_->base_path)) {
+ + ]
642 : 2 : impl_->base_path += "_dir";
643 : : }
644 : :
645 : 109 : std::filesystem::create_directories(impl_->base_path);
646 : :
647 [ + - + - : 1260 : for (const auto& entry : std::filesystem::directory_iterator(impl_->base_path)) {
+ + ]
648 [ + - + - : 933 : if (entry.is_regular_file() && entry.path().extension() == ".log") {
+ - + - +
- + - + -
+ - - - -
- ]
649 [ + - ]: 933 : auto file_info = parse_timestamp_file(entry.path());
650 : :
651 [ + - ]: 933 : if (file_info.is_valid) {
652 [ + - ]: 933 : impl_->timestamp_files.emplace_back(std::move(file_info));
653 : : }
654 : 933 : }
655 : 109 : }
656 : :
657 [ + + ]: 109 : if (impl_->timestamp_files.empty()) {
658 : 7 : rotate_timestamped();
659 : 7 : return;
660 : : }
661 : :
662 [ + - ]: 102 : std::sort(impl_->timestamp_files.begin(), impl_->timestamp_files.end(),
663 : 2868 : [](const LoggerFileInfo& lhs, const LoggerFileInfo& rhs) {
664 [ + - ]: 2868 : if (lhs.index != rhs.index) {
665 : 2868 : return lhs.index < rhs.index;
666 : : }
667 : :
668 : 0 : return lhs.timestamp < rhs.timestamp;
669 : : });
670 : :
671 [ + + ]: 104 : while (impl_->timestamp_files.size() > impl_->config.max_files) {
672 : 2 : std::error_code error;
673 : 2 : (void)std::filesystem::remove(impl_->timestamp_files.front().path, error);
674 : :
675 [ - + ]: 2 : if (error) {
676 : : break; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
677 : : }
678 : :
679 : 2 : impl_->timestamp_files.pop_front();
680 : : }
681 : :
682 : 102 : impl_->current_index = impl_->timestamp_files.back().index;
683 : 102 : impl_->current_path = impl_->timestamp_files.back().path;
684 : :
685 [ + + ]: 102 : if (impl_->config.append) {
686 : 2 : open_current(true, false);
687 : :
688 [ - + ]: 2 : if (!impl_->file) {
689 : 0 : rotate_timestamped();
690 : : }
691 : : } else {
692 : 100 : rotate_timestamped();
693 : : }
694 : : }
695 : :
696 : 201 : void LoggerBackend::open_current(bool append, bool report_error) {
697 : 201 : close_current();
698 : :
699 : 201 : int error_number = 0;
700 [ + + ]: 201 : impl_->file = open_log_file(impl_->current_path, append, error_number);
701 : :
702 [ - + ]: 199 : if (!impl_->file) {
703 [ # # ]: 0 : if (report_error) {
704 [ # # ]: 0 : std::string error_message{"logger backend: failed to open log file "};
705 [ # # # # ]: 0 : error_message.append(impl_->current_path.string());
706 [ # # # # : 0 : error_message.append(": ").append(std::error_code(error_number, std::generic_category()).message());
# # ]
707 : 0 : fail(error_message);
708 : 0 : }
709 : :
710 : 0 : return;
711 : : }
712 : :
713 [ - + ]: 199 : if (!get_log_file_size(impl_->file, impl_->current_size, error_number)) {
714 : : // LCOV_EXCL_START GCOVR_EXCL_START
715 : : close_current();
716 : :
717 : : if (report_error) {
718 : : std::string error_message{"logger backend: failed to query log file size "};
719 : : error_message.append(impl_->current_path.string());
720 : : error_message.append(": ").append(std::error_code(error_number, std::generic_category()).message());
721 : : fail(error_message);
722 : : }
723 : :
724 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
725 : : }
726 : : }
727 : :
728 : 388 : void LoggerBackend::close_current() noexcept {
729 [ + + ]: 388 : if (impl_->file) {
730 : 199 : std::fclose(impl_->file);
731 : 199 : impl_->file = nullptr;
732 : : }
733 : 388 : }
734 : :
735 : 28 : void LoggerBackend::rotate_fixed() {
736 : 28 : close_current();
737 : :
738 [ + + ]: 81 : for (size_t index = impl_->config.max_files; index > 0U; --index) {
739 [ + - ]: 55 : const auto source = fixed_file_path(impl_->base_path, index - 1U);
740 : 55 : std::error_code exists_error;
741 : 55 : const bool source_exists = std::filesystem::exists(source, exists_error);
742 : :
743 [ - + ]: 55 : if (exists_error) {
744 : : // LCOV_EXCL_START GCOVR_EXCL_START
745 : : std::string error_message{"logger backend: failed to inspect "};
746 : : error_message.append(source.string());
747 : : error_message.append(": ").append(exists_error.message());
748 : : fail(error_message);
749 : : return;
750 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
751 : 0 : }
752 : :
753 [ + + ]: 55 : if (!source_exists) {
754 : 7 : continue;
755 : : }
756 : :
757 [ + - ]: 48 : const auto target = fixed_file_path(impl_->base_path, index);
758 : 48 : std::error_code error;
759 : 48 : std::filesystem::remove(target, error);
760 : 48 : error.clear();
761 : 48 : std::filesystem::rename(source, target, error);
762 : :
763 [ + + ]: 48 : if (error) {
764 [ + - ]: 2 : std::this_thread::sleep_for(std::chrono::milliseconds(100));
765 : 2 : error.clear();
766 : 2 : std::filesystem::remove(target, error);
767 : 2 : error.clear();
768 : 2 : std::filesystem::rename(source, target, error);
769 : : }
770 : :
771 [ + + ]: 48 : if (error) {
772 [ + - ]: 2 : std::string error_message{"logger backend: failed to rotate "};
773 [ + - + - : 2 : error_message.append(source.string()).append(" to ").append(target.string());
+ - + - +
- ]
774 [ + - + - : 2 : error_message.append(": ").append(error.message());
+ - ]
775 : 2 : fail(error_message);
776 : 2 : return;
777 : 2 : }
778 [ + + + + : 57 : }
+ ]
779 : :
780 : 26 : impl_->current_path = impl_->base_path;
781 : 26 : open_current(false);
782 : : }
783 : :
784 : 135 : void LoggerBackend::rotate_timestamped() {
785 : 135 : const auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
786 : 135 : std::tm time_info{};
787 : 135 : bool converted = false;
788 : :
789 : : #if defined(_WIN32)
790 : : if (impl_->config.use_utc) {
791 : : converted = gmtime_s(&time_info, &now) == 0;
792 : : } else {
793 : : converted = localtime_s(&time_info, &now) == 0;
794 : : }
795 : : #else
796 [ + + ]: 135 : if (impl_->config.use_utc) {
797 : 36 : converted = gmtime_r(&now, &time_info) != nullptr;
798 : : } else {
799 : 99 : converted = localtime_r(&now, &time_info) != nullptr;
800 : : }
801 : : #endif
802 : :
803 [ - + ]: 135 : if VUNLIKELY (!converted) {
804 : : fail("logger backend: failed to convert timestamped log filename time"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
805 : 1 : return;
806 : : }
807 : :
808 : : char timestamp[32];
809 : 135 : const size_t size = std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H-%M-%S", &time_info);
810 : :
811 [ - + ]: 135 : if (size == 0U) {
812 : : fail("logger backend: failed to generate timestamped log filename"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
813 : 0 : return;
814 : : }
815 : :
816 : 135 : LoggerFileInfo new_file;
817 [ + - ]: 135 : new_file.timestamp.assign(timestamp, size);
818 : :
819 [ + + ]: 135 : if (impl_->current_index == std::numeric_limits<size_t>::max()) {
820 : 1 : fail("logger backend: timestamped log file index overflow");
821 : 1 : return;
822 : : }
823 : :
824 : 134 : new_file.index = impl_->current_index + 1U;
825 [ + - + - : 134 : new_file.path = impl_->base_path / (new_file.timestamp + "." + std::to_string(new_file.index) + ".log");
+ - + - +
- + - ]
826 : :
827 : 134 : impl_->current_index = new_file.index;
828 [ + - ]: 134 : impl_->current_path = new_file.path;
829 : :
830 [ + - ]: 134 : open_current(false);
831 : :
832 [ - + ]: 134 : if VUNLIKELY (impl_->has_error.load(std::memory_order_acquire)) {
833 : 0 : return;
834 : : }
835 : :
836 [ + - ]: 134 : impl_->timestamp_files.emplace_back(std::move(new_file));
837 : :
838 [ + + ]: 248 : while (impl_->timestamp_files.size() > impl_->config.max_files) {
839 : 116 : std::error_code error;
840 : 116 : (void)std::filesystem::remove(impl_->timestamp_files.front().path, error);
841 : :
842 [ + + ]: 116 : if (error) {
843 : 2 : break;
844 : : }
845 : :
846 : 114 : impl_->timestamp_files.pop_front();
847 : : }
848 [ + + ]: 135 : }
849 : :
850 : 1309 : void LoggerBackend::flush_output() {
851 : 1309 : int flush_result = 0;
852 : :
853 : : #if defined(_WIN32)
854 : : flush_result = ::_fflush_nolock(impl_->file);
855 : : #else
856 : 1309 : flush_result = std::fflush(impl_->file);
857 : : #endif
858 : :
859 [ + + ]: 1309 : if VUNLIKELY (flush_result != 0) {
860 : 2 : const int error_number = errno;
861 [ + - ]: 2 : std::string error_message{"logger backend: failed to flush log file "};
862 [ + - + - ]: 2 : error_message.append(impl_->current_path.string());
863 [ + - + - : 2 : error_message.append(": ").append(std::error_code(error_number, std::generic_category()).message());
+ - ]
864 : 2 : fail(error_message);
865 : 2 : }
866 : 1309 : }
867 : :
868 : 14321 : void LoggerBackend::write_output(std::string_view data) {
869 : 43110 : const auto exceeds_limit = [this, data](size_t current_size) {
870 [ + + + + ]: 14378 : return data.size() > impl_->config.max_file_size || current_size > impl_->config.max_file_size - data.size();
871 : 14321 : };
872 : :
873 : 14321 : const bool needs_rotation = exceeds_limit(impl_->current_size);
874 [ + + ]: 14323 : size_t new_size = needs_rotation ? impl_->config.max_file_size : impl_->current_size + data.size();
875 : :
876 [ + + ]: 14323 : if VUNLIKELY (needs_rotation) {
877 [ + - ]: 59 : flush_output();
878 : :
879 [ - + ]: 59 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
880 : 2 : return;
881 : : }
882 : :
883 : 59 : size_t real_size = 0U;
884 : 59 : int error_number = 0;
885 : :
886 [ - + ]: 59 : if (!get_log_file_size(impl_->file, real_size, error_number)) {
887 : : // LCOV_EXCL_START GCOVR_EXCL_START
888 : : std::string error_message{"logger backend: failed to query active log file size "};
889 : : error_message.append(impl_->current_path.string());
890 : : error_message.append(": ").append(std::error_code(error_number, std::generic_category()).message());
891 : : fail(error_message);
892 : : return;
893 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
894 : 0 : }
895 : :
896 [ + + + - : 59 : if (real_size > 0U && exceeds_limit(real_size)) {
+ + ]
897 [ + + ]: 55 : if (impl_->config.fixed_filename) {
898 [ + - ]: 27 : rotate_fixed();
899 : : } else {
900 [ + - ]: 28 : rotate_timestamped();
901 : : }
902 : :
903 [ + + ]: 55 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
904 : 2 : return;
905 : : }
906 : :
907 : 53 : new_size = data.size();
908 : : } else {
909 : 4 : new_size = real_size + data.size();
910 : : }
911 : : }
912 : :
913 : 14321 : size_t written = 0U;
914 : :
915 : : #if defined(_WIN32)
916 : : written = ::_fwrite_nolock(data.data(), sizeof(char), data.size(), impl_->file);
917 : : #elif defined(__linux__) && (!defined(__ANDROID__) || (defined(__ANDROID_API__) && __ANDROID_API__ >= 28))
918 [ + - ]: 14321 : written = ::fwrite_unlocked(data.data(), sizeof(char), data.size(), impl_->file);
919 : : #else
920 : : written = std::fwrite(data.data(), sizeof(char), data.size(), impl_->file);
921 : : #endif
922 : :
923 [ - + ]: 14317 : if VUNLIKELY (written != data.size()) {
924 : 0 : const int error_number = errno;
925 [ # # ]: 0 : std::string error_message{"logger backend: failed to write log file "};
926 [ # # # # ]: 0 : error_message.append(impl_->current_path.string());
927 [ # # # # : 0 : error_message.append(": ").append(std::error_code(error_number, std::generic_category()).message());
# # ]
928 : 0 : fail(error_message);
929 : 0 : return;
930 : 0 : }
931 : :
932 : 14317 : impl_->current_size = new_size;
933 : : }
934 : :
935 : 174 : void LoggerBackend::update_timestamp(int64_t seconds) {
936 : : if constexpr (!std::numeric_limits<std::time_t>::is_signed) {
937 : : if VUNLIKELY (seconds < 0) {
938 : : fail("logger backend: timestamp is outside time_t range");
939 : : return;
940 : : }
941 : : }
942 : :
943 : 174 : const auto time = static_cast<std::time_t>(seconds);
944 : :
945 : : if constexpr (sizeof(std::time_t) < sizeof(int64_t)) {
946 : : if VUNLIKELY (static_cast<int64_t>(time) != seconds) {
947 : : fail("logger backend: timestamp is outside time_t range");
948 : : return;
949 : : }
950 : : }
951 : :
952 : 174 : std::tm time_info{};
953 : 174 : bool converted = false;
954 : :
955 : : #if defined(_WIN32)
956 : : if (impl_->config.use_utc) {
957 : : converted = gmtime_s(&time_info, &time) == 0;
958 : : } else {
959 : : converted = localtime_s(&time_info, &time) == 0;
960 : : }
961 : : #else
962 [ + + ]: 174 : if (impl_->config.use_utc) {
963 : 37 : converted = gmtime_r(&time, &time_info) != nullptr;
964 : : } else {
965 : 137 : converted = localtime_r(&time, &time_info) != nullptr;
966 : : }
967 : : #endif
968 : :
969 [ - + ]: 174 : if VUNLIKELY (!converted) {
970 : : fail("logger backend: failed to convert log timestamp"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
971 : 0 : return;
972 : : }
973 : :
974 : 348 : impl_->timestamp_size =
975 : 174 : std::strftime(impl_->timestamp_prefix, sizeof(impl_->timestamp_prefix), "%m-%d %H:%M:%S.", &time_info);
976 : :
977 [ - + ]: 174 : if (impl_->timestamp_size == 0U) {
978 : : fail("logger backend: failed to format timestamp"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
979 : 0 : return;
980 : : }
981 : :
982 : 174 : impl_->cached_seconds = seconds;
983 : : }
984 : :
985 : 14327 : std::string_view LoggerBackend::format(const LoggerRecord& record) {
986 [ + - ]: 14327 : const auto milliseconds = std::chrono::floor<std::chrono::milliseconds>(record.timestamp.time_since_epoch()).count();
987 : 14327 : auto seconds = milliseconds / 1000;
988 : 14327 : int millisecond = static_cast<int>(milliseconds % 1000);
989 : :
990 [ - + ]: 14327 : if VUNLIKELY (millisecond < 0) {
991 : : // LCOV_EXCL_START GCOVR_EXCL_START
992 : : millisecond += 1000;
993 : : --seconds;
994 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
995 : : }
996 : :
997 [ + + ]: 14327 : if VUNLIKELY (seconds != impl_->cached_seconds) {
998 [ + - ]: 174 : update_timestamp(seconds);
999 : :
1000 [ - + ]: 174 : if VUNLIKELY (impl_->cached_seconds != seconds) {
1001 : 0 : return {};
1002 : : }
1003 : : }
1004 : :
1005 : 14326 : impl_->format_buffer.clear();
1006 [ + - ]: 14326 : impl_->format_buffer.append(impl_->timestamp_prefix, impl_->timestamp_size);
1007 : :
1008 : : char number_buffer[32];
1009 : : auto [millisecond_end, millisecond_error] =
1010 [ + - ]: 14327 : std::to_chars(number_buffer, number_buffer + sizeof(number_buffer), millisecond);
1011 : :
1012 [ - + ]: 14327 : if VUNLIKELY (millisecond_error != std::errc()) {
1013 : : fail("logger backend: failed to format milliseconds"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
1014 : 0 : return {};
1015 : : }
1016 : :
1017 : 14327 : const auto millisecond_size = static_cast<size_t>(millisecond_end - number_buffer);
1018 [ + - ]: 14327 : impl_->format_buffer.append(3U - millisecond_size, '0');
1019 [ + - ]: 14327 : impl_->format_buffer.append(number_buffer, millisecond_size);
1020 : :
1021 [ + + ]: 14326 : if VUNLIKELY (impl_->config.use_utc) {
1022 [ + - ]: 10198 : impl_->format_buffer.append(" UTC");
1023 : : }
1024 : :
1025 [ + - ]: 14327 : impl_->format_buffer.append(" @");
1026 : : auto [thread_end, thread_error] =
1027 [ + - ]: 14327 : std::to_chars(number_buffer, number_buffer + sizeof(number_buffer), record.thread_id);
1028 : :
1029 [ - + ]: 14326 : if VUNLIKELY (thread_error != std::errc()) {
1030 : : fail("logger backend: failed to format thread id"); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
1031 : 0 : return {};
1032 : : }
1033 : :
1034 [ + - ]: 14326 : impl_->format_buffer.append(number_buffer, static_cast<size_t>(thread_end - number_buffer));
1035 [ + - ]: 14326 : impl_->format_buffer.append(" - ");
1036 [ + - ]: 14327 : impl_->format_buffer.append(get_backend_level_string(record.level));
1037 [ + - ]: 14325 : impl_->format_buffer.append(" - ");
1038 [ + - ]: 14326 : impl_->format_buffer.append(record.message);
1039 [ + - ]: 14326 : impl_->format_buffer.push_back('\n');
1040 : :
1041 : 14327 : return impl_->format_buffer;
1042 : : }
1043 : :
1044 : 13 : void LoggerBackend::fail(std::string_view message) noexcept {
1045 : 13 : impl_->accepting.store(false, std::memory_order_release);
1046 : 13 : bool expected = false;
1047 : :
1048 [ + - + + : 26 : if (impl_->has_error.compare_exchange_strong(expected, true, std::memory_order_acq_rel, std::memory_order_acquire) &&
+ + ]
1049 : 13 : impl_->error_handler) {
1050 : : try {
1051 [ + + ]: 11 : impl_->error_handler(message);
1052 [ + - ]: 1 : } catch (const std::exception& error) {
1053 : 1 : std::fprintf(stderr, "LoggerBackend error handler failed: %s\n", error.what());
1054 : 1 : std::fflush(stderr);
1055 : 1 : } catch (...) {
1056 : 0 : std::fputs("LoggerBackend error handler failed with an unknown exception.\n", stderr);
1057 : 0 : std::fflush(stderr);
1058 : 0 : }
1059 : : }
1060 : 13 : }
1061 : :
1062 : 816 : void LoggerBackend::flush_file() noexcept {
1063 [ + + ]: 816 : if VUNLIKELY (impl_->has_error.load(std::memory_order_acquire)) {
1064 : 18 : return;
1065 : : }
1066 : :
1067 : : try {
1068 [ + - ]: 798 : flush_output();
1069 [ - - ]: 0 : } catch (const std::exception& error) {
1070 : 0 : fail(error.what());
1071 : : // LCOV_EXCL_START GCOVR_EXCL_START
1072 : : } catch (...) {
1073 : : fail("logger backend: failed to flush log file");
1074 : : }
1075 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
1076 : : }
1077 : :
1078 : 14319 : void LoggerBackend::write(std::unique_ptr<LoggerRecord>&& record) noexcept {
1079 [ - + ]: 14319 : if VUNLIKELY (impl_->has_error.load(std::memory_order_acquire)) {
1080 : 0 : return;
1081 : : }
1082 : :
1083 : : try {
1084 : 14320 : const auto level = record->level;
1085 : 14320 : bool wrote = false;
1086 : :
1087 [ + + ]: 14320 : if VUNLIKELY (impl_->backtrace_enabled) {
1088 [ + + ]: 17 : if VUNLIKELY (level >= Logger::kWarn) {
1089 [ + - ]: 7 : const auto formatted = format(*record);
1090 : :
1091 [ - + ]: 7 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
1092 : 0 : return;
1093 : : }
1094 : :
1095 [ + - ]: 7 : write_output(formatted);
1096 : :
1097 [ - + ]: 7 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
1098 : 0 : return;
1099 : : }
1100 : :
1101 [ + + + + : 7 : if (impl_->console_writer && !impl_->invoking_console) {
+ + ]
1102 : 3 : impl_->console_buffer.swap(impl_->format_buffer);
1103 : 3 : impl_->invoking_console = true;
1104 : :
1105 : : try {
1106 : 3 : const std::string_view console_log(impl_->console_buffer);
1107 [ + - + + ]: 3 : impl_->console_writer(level, console_log.substr(0U, console_log.size() - 1U));
1108 : 1 : } catch (...) {
1109 : 1 : impl_->invoking_console = false;
1110 : 1 : throw;
1111 : 1 : }
1112 : :
1113 : 2 : impl_->invoking_console = false;
1114 : : }
1115 : :
1116 : 6 : wrote = true;
1117 : : }
1118 : :
1119 [ + + ]: 16 : if VLIKELY (impl_->backtrace_capacity > 0U) {
1120 [ + - ]: 13 : impl_->backtrace.emplace_back(std::move(record));
1121 : :
1122 [ + + ]: 13 : if VLIKELY (impl_->backtrace.size() > impl_->backtrace_capacity) {
1123 : 1 : impl_->backtrace.pop_front();
1124 : : }
1125 : : }
1126 : : } else {
1127 [ + - ]: 14303 : const auto formatted = format(*record);
1128 : :
1129 [ - + ]: 14302 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
1130 : 2 : return;
1131 : : }
1132 : :
1133 [ + - ]: 14302 : write_output(formatted);
1134 : :
1135 [ + + ]: 14299 : if VUNLIKELY (impl_->has_error.load(std::memory_order_relaxed)) {
1136 : 2 : return;
1137 : : }
1138 : :
1139 : 14299 : wrote = true;
1140 : : }
1141 : :
1142 [ + + + + : 14316 : if (wrote && impl_->config.flush_interval_ms == 0U) {
+ + ]
1143 [ + - ]: 109 : flush_output();
1144 [ + + + + : 14205 : } else if VUNLIKELY (wrote && level >= Logger::kError) {
+ + ]
1145 [ + - ]: 340 : flush_output();
1146 : : }
1147 [ - + ]: 1 : } catch (const std::exception& error) {
1148 : 0 : fail(error.what());
1149 : 1 : } catch (...) {
1150 : 1 : fail("logger backend: failed to write a log record");
1151 : 1 : }
1152 : : }
1153 : :
1154 : 451 : void LoggerBackend::barrier(Callback&& callback) noexcept {
1155 : 451 : auto invoke_callback = [this, &callback] {
1156 : : try {
1157 [ + - ]: 451 : callback();
1158 : : // LCOV_EXCL_START GCOVR_EXCL_START
1159 : : } catch (const std::exception& error) {
1160 : : fail(error.what());
1161 : : } catch (...) {
1162 : : fail("logger backend: control callback failed");
1163 : : }
1164 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
1165 : 451 : };
1166 : :
1167 [ + + ]: 451 : if (is_in_same_thread()) {
1168 : 9 : invoke_callback();
1169 : 19 : return;
1170 : : }
1171 : :
1172 [ + + + + : 442 : if VUNLIKELY (is_ready_to_quit() || !is_running()) {
+ + ]
1173 : 10 : wait_for_quit(Timer::kInfinite, false);
1174 : 10 : std::lock_guard lock(impl_->stopped_mtx);
1175 : 10 : invoke_callback();
1176 : :
1177 : 10 : return;
1178 : 10 : }
1179 : :
1180 : : try {
1181 : 432 : PostTaskOptions options;
1182 : 432 : options.overflow_policy = TaskOverflowPolicy::kBlock;
1183 : 432 : options.drop_policy = TaskDropPolicy::kProtected;
1184 : :
1185 [ + - + - ]: 863 : auto handle = post_task_handle([&invoke_callback] { invoke_callback(); }, options);
1186 [ + - ]: 432 : (void)handle.wait();
1187 : :
1188 [ + + ]: 432 : if VUNLIKELY (handle.state() != TaskExecutionState::kCompleted) {
1189 [ + - ]: 1 : wait_for_quit(Timer::kInfinite, false);
1190 [ + - ]: 1 : std::lock_guard lock(impl_->stopped_mtx);
1191 [ + - ]: 1 : invoke_callback();
1192 : 1 : }
1193 : : // LCOV_EXCL_START GCOVR_EXCL_START
1194 : : } catch (const std::exception& error) {
1195 : : fail(error.what());
1196 : : } catch (...) {
1197 : : fail("logger backend: failed to enqueue a control barrier");
1198 : : }
1199 : : // LCOV_EXCL_STOP GCOVR_EXCL_STOP
1200 : : }
1201 : :
1202 : : } // namespace vlink
|