autotoc_md825
doc_id: "LOG-API-002a" doc_title: "API Reference - Core" doc_version: "1.0.0" doc_date: "2026-04-04" doc_status: "Released" project: "logger_system"
category: "API"
Language: English | 한국어
API Reference - Core
Split from: API_REFERENCE.md
Version: 0.5.0.0 Last Updated: 2026-02-08
Table of Contents
- Overview
- Core Classes
- ILogger Interface (Phase 2.0)
- Unified Log Context (v3.3.0)
- Scoped Context Guard (v3.3.0)
- Structured Log Builder (v3.1.0)
- Writer Builder (v4.1.0)
- Configuration
- Builder Pattern
- Configuration Strategies
- Interfaces
- Error Handling
Overview
The Logger System (v5.0) provides a high-performance, thread-safe logging framework with:
- Dual API Design: Supports both
common::interfaces::ILogger (standardized) and native logger_system::log_level (backward compatible)
- Standalone Mode: No external dependencies required (uses
std::jthread internally)
- Optional Integration: Thread_system integration is optional since v3.0
- C++20 Features: Leverages Concepts and
source_location for enhanced developer experience
- Unified Log Context (v3.3.0): Thread-safe, category-based context management with type-safe storage
- Structured Logging (v3.1.0): Fluent builder API for creating structured log entries with arbitrary fields
- Writer Builder (v4.1.0): Fluent decorator composition for building complex writer configurations
- Log Sampling (v3.3.0): Multiple sampling strategies (random, rate limiting, adaptive, hash-based) for high-volume scenarios
- Real-time Analysis (v3.2.0): Anomaly detection with error spike, pattern matching, and rate anomaly alerts
Namespace
All classes are in the kcenon::logger namespace:
Console writer for logging to stdout/stderr.
High-performance, thread-safe logging system with asynchronous capabilities.
Builder pattern implementation for flexible logger configuration kcenon.
Core Classes
kcenon::logger::logger
The main logger class that handles all logging operations. Implements both common::interfaces::ILogger for standardized interface and security::critical_logger_interface for crash-safe logging.
Constructor
explicit logger(
bool async =
true,
std::size_t buffer_size = 8192,
std::unique_ptr<backends::integration_backend> backend = nullptr);
Parameters:
async: Enable asynchronous logging (default: true)
buffer_size: Size of the log buffer in bytes (default: 8192)
backend: Integration backend for async processing (default: auto-detected standalone backend)
Destructor
Ensures all buffered messages are flushed before destruction.
ILogger Interface (Phase 2.0)
Since v2.0, the logger implements common::interfaces::ILogger for standardized logging across the unified_system ecosystem.
Log Methods (ILogger Interface)
const std::string& message) override;
std::string_view message,
const common::source_location& loc = common::source_location::current()) override;
const std::string& message,
const std::string& file,
int line,
const std::string& function) override;
Level Management (ILogger Interface)
bool is_enabled(common::interfaces::log_level level) const override;
common::interfaces::log_level get_level() const override;
Native API (Backward Compatible)
For backward compatibility with logger_system native types:
void log(log_level level, const std::string& message);
void log(log_level level, const std::string& message,
const std::string& file, int line, const std::string& function);
void log(log_level level, const std::string& message,
bool is_enabled(log_level level) const;
void set_min_level(log_level level);
log_level get_min_level() const;
Log context containing source location information.
Writer Management
common::VoidResult add_writer(
const std::string& name, std::unique_ptr<base_writer> writer);
bool remove_writer(const std::string& name);
Abstract base class for all log output writers.
Lifecycle Management
Metrics
bool is_metrics_collection_enabled() const;
std::chrono::seconds duration) const;
Filtering
void set_filter(std::unique_ptr<log_filter_interface> filter);
bool has_filter() const;
Emergency Flush (Signal Safety)
int get_emergency_fd() const override;
const char* get_emergency_buffer() const override;
size_t get_emergency_buffer_size() const override;
Unified Log Context (v3.3.0)
Header: <kcenon/logger/core/unified_log_context.h>
kcenon::logger::unified_log_context
A thread-safe, category-based context manager that consolidates all logging context into a single interface. Replaces the previous scattered approach of managing context through separate mechanisms (log_context_storage, otel_context_storage, etc.).
Value Type
using context_value = std::variant<std::monostate, bool, int64_t, double, std::string>;
std::variant< std::monostate, bool, int64_t, double, std::string > context_value
Value type for unified context storage.
Supports common types used in logging context. std::monostate represents null/unset values.
Context Categories
custom = 0,
trace = 1,
request = 2,
otel = 3
};
context_category
Categories for organizing context entries.
Constructor
Unified interface for managing all types of logging context.
Setters
std::string_view span_id,
std::optional<std::string_view> parent_span_id = std::nullopt);
std::optional<std::string_view> correlation_id = std::nullopt);
OpenTelemetry context for trace correlation.
Getters
[[nodiscard]] std::optional<context_value> get(std::string_view key) const;
template <typename T>
[[nodiscard]] std::optional<T> get_as(std::string_view key) const;
[[nodiscard]] std::string get_string(std::string_view key,
std::string_view default_value = "") const;
[[nodiscard]] std::optional<context_category> get_category(std::string_view key) const;
Query Methods
[[nodiscard]] bool has(std::string_view key) const;
[[nodiscard]] bool empty() const;
[[nodiscard]] size_t size() const;
[[nodiscard]] std::vector<std::string> keys() const;
Removal and Export
void remove(std::string_view key);
void clear();
std::unordered_map< std::string, log_value > log_fields
Type alias for structured fields map.
Usage Example
ctx.
set(
"user_id", int64_t{12345});
ctx.
set(
"session_active",
true);
ctx.
set(
"latency_ms", 42.5);
ctx.
set_trace(
"0af7651916cd43dd8448eb211c80319c",
"b7ad6b7169203331");
auto user_id = ctx.
get_as<int64_t>(
"user_id");
auto trace_keys = ctx.
keys(context_category::trace);
ctx.
clear(context_category::trace);
unified_log_context & set_trace(std::string_view trace_id, std::string_view span_id, std::optional< std::string_view > parent_span_id=std::nullopt)
Set trace context.
std::vector< std::string > keys() const
Get all keys in the context.
unified_log_context & set_request(std::string_view request_id, std::optional< std::string_view > correlation_id=std::nullopt)
Set request context.
void clear()
Clear all entries from the context.
std::string get_string(std::string_view key, std::string_view default_value="") const
Get a context value as string.
unified_log_context & set(std::string_view key, context_value value, context_category category=context_category::custom)
Set a context value.
std::optional< T > get_as(std::string_view key) const
log_fields to_fields() const
Export context to log_fields format.
Unified interface for managing all types of logging context.
Thread Safety
All methods are thread-safe. Read operations use shared locks, write operations use exclusive locks (uses std::shared_mutex internally).
Scoped Context Guard (v3.3.0)
Header: <kcenon/logger/core/scoped_context_guard.h>
kcenon::logger::scoped_context_guard
RAII guard for exception-safe context management. Saves the current context state on construction and restores it on destruction.
Constructor
std::string_view key,
RAII guard for automatic context management.
Setters (Chainable)
std::string_view span_id,
std::optional<std::string_view> parent_span_id = std::nullopt);
std::optional<std::string_view> correlation_id = std::nullopt);
Usage Example
void handle_request(
logger& log,
const Request& req) {
guard.set_request(req.id(), req.correlation_id())
.set("user_id", int64_t{req.user_id()})
.set("endpoint", std::string{req.path()});
{
step_guard.set("step", std::string{"validation"});
}
}
structured_log_builder log_structured(log_level level)
void emit()
Emit the log entry.
structured_log_builder & message(const std::string &msg)
Set the log message.
RAII guard for automatic context restoration.
The guard is non-copyable but movable. Each instance should be used from a single thread.
Structured Log Builder (v3.1.0)
Header: <kcenon/logger/core/structured_log_builder.h>
kcenon::logger::structured_log_builder
Fluent builder for creating structured log entries with arbitrary key-value fields. Integrates with the main logger class through the log_structured() method.
Constructor
emit_callback callback,
Fluent builder for creating structured log entries.
Note: Builders are typically created through the logger's log_structured() method, not constructed directly.
Builder Methods
void emit();
std::variant< std::string, int64_t, double, bool > log_value
Value type for structured logging fields.
Logger Integration (log_structured)
The canonical way to create a structured log entry is through the logger's log_structured() method:
Context fields set via set_context() on the logger are automatically included in all structured log entries.
Usage Example
logger->log_structured(log_level::info)
.message("User login")
.field("user_id", 12345)
.field("ip_address", "192.168.1.1")
.field("session_id", "abc-123")
.emit();
logger->log_structured(log_level::error)
.message("Database connection failed")
.field("retry_count", 3)
.field("db_host", "db-primary.internal")
.field("latency_ms", 1523.4)
.category("database")
.emit();
logger->set_context(
"request_id",
"req-789");
logger->set_context(
"trace_id",
"trace-456");
logger->log_structured(log_level::info)
.message("Processing request")
.field("step", "validation")
.emit();
Fluent builder for structured log entries kcenon.
Important: The builder does NOT auto-emit on destruction. You must explicitly call emit() to log the entry. If emit() is not called, the entry is silently discarded.
Thread Safety
Each builder instance should be used by a single thread. The emit() operation itself is thread-safe.
Writer Builder (v4.1.0)
Header: <kcenon/logger/builders/writer_builder.h>
kcenon::logger::writer_builder
Fluent builder for composing log writer decorators in a readable and maintainable way. Instead of manually nesting decorators, you chain method calls to build complex writer configurations.
The builder is move-only to ensure clear ownership semantics.
Core Writers (Terminal Nodes)
These methods set the base writer. Exactly one must be called before adding decorators.
writer_builder& file(const std::string& filename, bool append = true);
writer_builder& console(bool use_stderr = false, bool auto_detect_color = true);
writer_builder& custom(std::unique_ptr<log_writer_interface> writer);
Decorator Writers (Middleware)
These methods wrap the current writer with additional functionality. They can be chained in any order.
writer_builder& async(std::size_t queue_size = 10000,
std::chrono::seconds flush_timeout = std::chrono::seconds(5));
writer_builder& buffered(std::size_t max_entries = 100,
std::chrono::milliseconds flush_interval = std::chrono::milliseconds(5000));
writer_builder& filtered(std::unique_ptr<log_filter_interface> filter);
writer_builder& formatted(std::unique_ptr<log_formatter_interface> formatter);
RAII wrapper for encryption keys with secure memory management.
Build and Utility
bool has_core_writer() const noexcept;
void reset() noexcept;
std::unique_ptr< log_writer_interface > log_writer_ptr
Type alias for writer unique pointer.
Usage Examples
#include <kcenon/logger/builders/writer_builder.h>
auto writer = writer_builder()
.file("app.log")
.buffered(100)
.build();
auto console = writer_builder()
.console()
.filtered(std::make_unique<filters::level_filter>(log_level::warning))
.build();
auto key_result = security::secure_key_storage::generate_key(32);
auto secure_writer = writer_builder()
.file("secure.log.enc")
.encrypted(std::move(key_result.value()))
.buffered()
.async()
.build();
auto custom = writer_builder()
.custom(std::make_unique<my_custom_writer>())
.formatted(std::make_unique<json_formatter>(true))
.buffered(50)
.build();
Log filtering functionality.
Error Handling: Methods throw std::logic_error if called in invalid order (e.g., adding a decorator before setting a core writer, or setting two core writers).
Configuration
kcenon::logger::logger_config
Configuration structure with validation capabilities.
bool async = true;
std::size_t buffer_size = 8192;
logger_system::log_level min_level = logger_system::log_level::info;
std::size_t batch_size = 100;
std::chrono::milliseconds flush_interval{1000};
bool use_lock_free = false;
bool enable_batch_writing = false;
bool enable_metrics = false;
bool enable_crash_handler = false;
bool enable_structured_logging = false;
bool enable_color_output = true;
bool enable_timestamp = true;
bool enable_source_location = true;
std::size_t max_queue_size = 10000;
std::size_t max_writers = 16;
std::string log_directory = "";
std::string log_file_prefix = "app";
std::size_t max_file_size = 100 * 1024 * 1024;
std::size_t max_file_count = 5;
std::string remote_host = "";
uint16_t remote_port = 0;
std::chrono::milliseconds network_timeout{5000};
};
overflow_policy
Overflow policy for when buffers are full.
Configuration structure for logger with validation.
Static Factory Methods
Builder Pattern
kcenon::logger::logger_builder
Fluent interface for constructing logger instances with validation.
Basic Configuration
logger_builder& with_flush_interval(std::chrono::milliseconds interval);
Builder pattern for logger construction with validation.
Feature Flags
overflow_policy
Policy for handling queue overflow when max_queue_size is reached.
Output Configuration
const std::string& prefix = "app",
std::size_t max_size = 100 * 1024 * 1024,
std::size_t max_count = 5);
uint16_t port,
std::chrono::milliseconds timeout =
std::chrono::milliseconds(5000));
Writers and Filters
std::unique_ptr<base_writer> writer);
logger_builder& add_filter(std::unique_ptr<log_filter_interface> filter);
bool include_matches = true);
std::function<
bool(
const log_entry&)> predicate);
logger_builder& with_formatter(std::unique_ptr<log_formatter_interface> formatter);
Represents a single log entry with all associated metadata.
Backend Selection
logger_builder& with_backend(std::unique_ptr<backends::integration_backend> backend);
Environment and Error Handling
logger_error_code
Error codes specific to the logger system.
Build
Configuration Strategies
Deployment Strategy
development,
staging,
production,
testing
};
deployment_env
Deployment environment types.
Performance Strategy
low_latency,
balanced,
high_throughput,
minimal_overhead
};
performance_level
Performance tuning presets.
Environment Strategy
Supported environment variables:
LOG_LEVEL: trace, debug, info, warn, error, fatal
LOG_ASYNC: true/false
LOG_BUFFER_SIZE: buffer size in bytes
LOG_BATCH_SIZE: batch size
LOG_FLUSH_INTERVAL: flush interval in ms
LOG_COLOR: true/false
LOG_METRICS: true/false
LOG_ENV: production/staging/development/testing
Composite Strategy
logger_builder& apply_strategy(std::unique_ptr<config_strategy_interface> strategy);
Interfaces
kcenon::logger::log_writer_interface
public:
virtual bool is_healthy() const { return true; }
};
Base interface for all log writers and decorators.
kcenon::logger::log_filter_interface
public:
virtual bool should_log(
const log_entry& entry)
const = 0;
};
Interface for log filters.
kcenon::logger::log_formatter_interface
public:
virtual std::string format(
const log_entry& entry)
const = 0;
};
kcenon::logger::log_entry
logger_system::log_level level;
std::string message;
std::string file;
int line;
std::string function;
std::chrono::system_clock::time_point timestamp;
std::thread::id thread_id;
std::unordered_map<std::string, std::string> context;
};
Error Handling
Error Codes
Header: <kcenon/logger/core/error_codes.h>
success = 0,
unknown_error = 1,
not_implemented = 2,
invalid_argument = 3,
writer_not_found = 1000,
writer_initialization_failed = 1001,
writer_already_exists = 1002,
writer_not_healthy = 1003,
file_open_failed = 1100,
file_write_failed = 1101,
file_rotation_failed = 1102,
file_permission_denied = 1103,
network_connection_failed = 1200,
network_send_failed = 1201,
network_timeout = 1202,
buffer_overflow = 1300,
queue_full = 1301,
queue_stopped = 1302,
queue_overflow_dropped = 1303,
queue_overflow_blocked = 1304,
invalid_configuration = 1400,
configuration_missing = 1401,
configuration_conflict = 1402,
metrics_collection_failed = 1500,
metrics_not_available = 1501,
flush_timeout = 1600,
processing_failed = 1601,
filter_error = 1602,
formatter_error = 1603,
batch_processing_timeout = 1604,
batch_processing_failed = 1605,
encryption_failed = 1700,
decryption_failed = 1701,
authentication_failed = 1702,
sanitization_failed = 1703,
file_read_failed = 1704,
insecure_permissions = 1705,
path_traversal_detected = 1706,
invalid_key_size = 1707,
invalid_filename = 1708,
di_not_available = 1800,
component_not_found = 1801,
registration_failed = 1802,
creation_failed = 1803,
operation_failed = 1804,
async_operation_not_running = 1805,
async_operation_already_running = 1806,
writer_not_available = 1900,
writer_configuration_error = 1901,
writer_operation_failed = 1902,
destructor_cleanup_failed = 1903
};
Error Code Categories Summary
| Range | Category | Description |
| 0-999 | General | Success, unknown, not implemented, invalid argument |
| 1000-1099 | Writer | Writer lifecycle and health errors |
| 1100-1199 | File | File I/O, rotation, and permission errors |
| 1200-1299 | Network | Connection, send, and timeout errors |
| 1300-1399 | Buffer/Queue | Overflow, capacity, and state errors |
| 1400-1499 | Configuration | Validation, missing, and conflict errors |
| 1500-1599 | Metrics | Collection and availability errors |
| 1600-1699 | Processing | Flush, filter, formatter, and batch errors |
| 1700-1799 | Security | Encryption, path traversal, and permission errors |
| 1800-1899 | DI Container | Dependency injection lifecycle errors |
| 1900-1999 | Writer (ext.) | Extended writer operation errors |
Result Types
The logger uses common::Result<T> and common::VoidResult from common_system:
return common::make_error<void>(
common::ErrorCategory::Logger,
static_cast<int>(logger_error_code::queue_full),
"Queue is full"
);
Helper Functions
const std::string& message = "");
kcenon::logger::result<T> Wrapper
A typed result wrapper built on top of the common::Result<T> pattern:
template<typename T>
public:
static result ok_value(
const T& value);
bool has_value() const;
explicit operator bool() const;
T& value();
const T& value() const;
const std::string& error_message() const;
};
Last Updated: 2026-02-08