Logger System 0.1.3
High-performance C++20 thread-safe logging system with asynchronous capabilities
Loading...
Searching...
No Matches
buffered_writer.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
5#pragma once
6
42
44
45#include <atomic>
46#include <chrono>
47#include <cstdint>
48#include <mutex>
49#include <vector>
50
51namespace kcenon::logger {
52
82public:
86 static constexpr size_t DEFAULT_BUFFER_SIZE = 100;
87
91 static constexpr std::chrono::milliseconds DEFAULT_FLUSH_INTERVAL{5000};
92
105 explicit buffered_writer(
106 std::unique_ptr<log_writer_interface> wrapped,
107 size_t max_entries = DEFAULT_BUFFER_SIZE,
108 std::chrono::milliseconds flush_interval = DEFAULT_FLUSH_INTERVAL);
109
119 ~buffered_writer() override;
120
121 // Non-copyable
124
125 // Non-movable (mutex is not movable)
128
142 common::VoidResult write(const log_entry& entry) override;
143
156 common::VoidResult flush() override;
157
165 size_t get_buffer_count() const;
166
174 size_t get_max_entries() const noexcept;
175
183 std::chrono::milliseconds get_flush_interval() const noexcept;
184
188 struct stats {
189 std::atomic<uint64_t> total_entries_written{0};
190 std::atomic<uint64_t> total_flushes{0};
191 std::atomic<uint64_t> flush_on_full{0};
192 std::atomic<uint64_t> flush_on_interval{0};
193 std::atomic<uint64_t> manual_flushes{0};
194 };
195
203 const stats& get_stats() const noexcept;
204
210 void reset_stats();
211
212private:
218 common::VoidResult flush_buffer_unsafe();
219
225 bool should_flush_by_time() const;
226
233 static log_entry copy_entry(const log_entry& entry);
234
235 size_t max_entries_;
236 std::chrono::milliseconds flush_interval_;
237
238 mutable std::mutex mutex_;
239 std::vector<log_entry> buffer_;
240 std::chrono::steady_clock::time_point last_flush_time_;
241
242 mutable stats stats_;
243};
244
257std::unique_ptr<buffered_writer> make_buffered_writer(
258 std::unique_ptr<log_writer_interface> writer,
259 size_t max_entries = buffered_writer::DEFAULT_BUFFER_SIZE,
260 std::chrono::milliseconds flush_interval = buffered_writer::DEFAULT_FLUSH_INTERVAL);
261
262} // namespace kcenon::logger
Decorator that buffers log entries before writing to wrapped writer.
buffered_writer & operator=(const buffered_writer &)=delete
buffered_writer & operator=(buffered_writer &&)=delete
buffered_writer(buffered_writer &&)=delete
buffered_writer(const buffered_writer &)=delete
Abstract base class for decorator pattern log writers.
Base interface for all log writers and decorators.
Base class for decorator pattern writers.
Data structures for representing log entries and source locations kcenon.
DLL export/import macros for logger_system shared library support.
#define LOGGER_SYSTEM_API
Statistics for the buffered writer.
Represents a single log entry with all associated metadata.
Definition log_entry.h:155