Logger System 0.1.3
High-performance C++20 thread-safe logging system with asynchronous capabilities
Loading...
Searching...
No Matches
console_sink.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
19#include <iostream>
20#include <mutex>
22
23namespace kcenon::logger {
24
53public:
66 explicit console_sink(bool use_stderr = false, bool auto_flush = false)
67 : use_stderr_(use_stderr)
68 , auto_flush_(auto_flush)
69 {}
70
76 ~console_sink() override {
77 flush(); // Ensure all data is written
78 }
79
95 common::VoidResult write_raw(std::string_view message) override {
96 std::lock_guard<std::mutex> lock(mutex_);
97
98 if (use_stderr_) {
99 std::cerr << message;
100 if (auto_flush_) {
101 std::cerr.flush();
102 }
103 } else {
104 std::cout << message;
105 if (auto_flush_) {
106 std::cout.flush();
107 }
108 }
109
110 return common::ok(); // Success
111 }
112
124 std::lock_guard<std::mutex> lock(mutex_);
125
126 if (use_stderr_) {
127 std::cerr.flush();
128 } else {
129 std::cout.flush();
130 }
131
132 return common::ok(); // Success
133 }
134
146 bool is_healthy() const override {
147 return true; // Console is always available
148 }
149
156 std::string get_name() const override {
157 return "console";
158 }
159
168 std::string get_info() const override {
169 std::string info = use_stderr_ ? "stderr" : "stdout";
170 if (auto_flush_) {
171 info += ", auto-flush";
172 }
173 return info;
174 }
175
184 void set_use_stderr(bool use_stderr) {
185 std::lock_guard<std::mutex> lock(mutex_);
186 use_stderr_ = use_stderr;
187 }
188
197 void set_auto_flush(bool auto_flush) {
198 std::lock_guard<std::mutex> lock(mutex_);
199 auto_flush_ = auto_flush;
200 }
201
202private:
205 mutable std::mutex mutex_;
206};
207
208} // namespace kcenon::logger
Outputs log messages to console (stdout or stderr)
common::VoidResult write_raw(std::string_view message) override
Write a pre-formatted message to console.
bool auto_flush_
Flush after every write.
console_sink(bool use_stderr=false, bool auto_flush=false)
Construct a console sink.
bool use_stderr_
Write to stderr instead of stdout.
std::mutex mutex_
Protects console output.
common::VoidResult flush() override
Flush buffered output to console.
bool is_healthy() const override
Check if console is healthy.
~console_sink() override
Destructor - ensures all data is flushed.
std::string get_name() const override
Get the name of this sink.
std::string get_info() const override
Get sink information.
void set_use_stderr(bool use_stderr)
Set whether to use stderr.
void set_auto_flush(bool auto_flush)
Set whether to auto-flush after every write.
Abstract interface for log output destinations (I/O only)
VoidResult ok()
Interface for log output destinations (Single Responsibility Principle) kcenon.