dmsc/c/
log.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Log Module C API
19//!
20//! This module provides C language bindings for DMSC's logging infrastructure. The logging module
21//! delivers structured, high-performance logging capabilities with multiple output destinations,
22//! configurable log levels, and rich formatting options. This C API enables C/C++ applications
23//! to leverage DMSC's logging system for comprehensive observability and debugging support.
24//!
25//! ## Module Architecture
26//!
27//! The logging module comprises two primary components that together provide complete logging
28//! functionality:
29//!
30//! - **DMSCLogConfig**: Configuration container for logger initialization parameters including log
31//!   level thresholds, output destinations, formatting options, and sink configurations. The
32//!   configuration object controls all aspects of logger behavior and resource allocation.
33//!
34//! - **DMSCLogger**: Primary logging interface providing methods for emitting log entries at
35//!   various severity levels. The logger instance handles log message formatting, filtering based
36//!   on configured levels, and routing to configured output sinks.
37//!
38//! ## Log Levels
39//!
40//! The logging system supports standard log severity levels:
41//!
42//! - **TRACE** (0): Most detailed level, typically used for debugging with very granular
43//!   information about program execution flow.
44//!
45//! - **DEBUG** (1): Detailed information for debugging purposes, useful during development
46//!   and troubleshooting.
47//!
48//! - **INFO** (2): General informational messages about normal application operation,
49//!   confirming that expected events have occurred.
50//!
51//! - **WARN** (3): Warning messages indicating potential issues that don't prevent the
52//!   application from functioning but may require attention.
53//!
54//! - **ERROR** (4): Error messages indicating failures that affect specific operations
55//!   but don't prevent the overall application from continuing.
56//!
57//! - **FATAL** (5): Critical errors that prevent continued operation, typically followed
58//!   by application shutdown or termination.
59//!
60//! ## Structured Logging
61//!
62//! The logger supports structured logging with key-value pairs:
63//!
64//! - **Context Fields**: Attach contextual information to log entries that provides
65//!   additional context for debugging and analysis.
66//!
67//! - **Automatic Fields**: Built-in fields including timestamp, log level, target/module,
68//!   thread ID, and line number information.
69//!
70//! - **Custom Fields**: User-defined fields for application-specific context like user IDs,
71//!   request IDs, operation types, and business metrics.
72//!
73//! - **Field Types**: Support for various field types including strings, integers, floats,
74//!   booleans, durations, and nested objects.
75//!
76//! ## Output Sinks
77//!
78//! The logging system supports multiple output destinations:
79//!
80//! - **Console Sink**: Standard output and standard error streams with colorized output
81//!   support for terminal environments.
82//!
83//! - **File Sink**: Rotating log files with configurable size and time-based rotation.
84//!   Supports log compression and retention policies.
85//!
86//! - **Syslog Sink**: Integration with system logging daemon (Unix/Linux systems).
87//!   Follows standard syslog protocols and priorities.
88//!
89//! - **Journald Sink**: Integration with systemd journal for Linux systems with structured
90//!   metadata support.
91//!
92//! - **Network Sink**: Remote log aggregation via TCP/UDP protocols. Supports buffering
93//!   and retry logic for unreliable networks.
94//!
95//! - **Custom Sinks**: User-defined sink implementations for integration with external
96//!   logging systems, databases, or cloud services.
97//!
98//! ## Log Formatting
99//!
100//! The logger provides configurable formatting options:
101//!
102//! - **Format Patterns**: Custom format strings using placeholders for log components.
103//!   Supports strftime-style time formatting.
104//!
105//! - **Structured Format**: JSON output for machine-readable logs suitable for log
106//!   aggregation and analysis tools.
107//!
108//! - **Pretty Print**: Human-readable output with colors and indentation for development
109//!   and debugging.
110//!
111//! - **Compact Format**: Minimal output for high-volume logging scenarios.
112//!
113//! ## Log Rotation
114//!
115//! File-based logging implements comprehensive rotation strategies:
116//!
117//! - **Size-Based Rotation**: Rotate when log file reaches specified size threshold.
118//!   Creates numbered backup files (.1, .2, etc.).
119//!
120//! - **Time-Based Rotation**: Rotate at specified time intervals (hourly, daily, weekly).
121//!   Supports timestamp-based file naming.
122//!
123//! - **Retention Policies**: Configure maximum number of log files to retain and maximum
124//!   total disk space for logs.
125//!
126//! - **Compression**: Automatic compression of rotated log files to save disk space.
127//!
128//! - **Async Write**: Non-blocking writes to disk to prevent logging from impacting
129//!   application performance.
130//!
131//! ## Performance Characteristics
132//!
133//! Logging operations are optimized for minimal performance impact:
134//!
135//! - **Log Level Filtering**: Compile-time and runtime level checks prevent unnecessary
136//!   message construction for disabled log levels.
137//!
138//! - **Async Logging**: Non-blocking API with background thread for log processing.
139//!   Producer-consumer pattern prevents slow I/O from blocking application.
140//!
141//! - **Batching**: Multiple log entries batched together for efficient I/O operations.
142//!
143//! - **Memory Allocation**: Arena-based string formatting reduces per-message allocations.
144//!
145//! - **Lazy Evaluation**: Structured fields evaluated only when log level is enabled.
146//!
147//! ## Memory Management
148//!
149//! All C API objects use opaque pointers with manual memory management:
150//!
151//! - Constructor functions allocate new instances on the heap
152//! - Destructor functions must be called to release memory
153//! - Logger instances should be freed during application shutdown
154//! - Log messages are managed internally by the logger
155//!
156//! ## Thread Safety
157//!
158//! The underlying implementations are thread-safe:
159//!
160//! - Concurrent log calls from multiple threads are synchronized internally
161//! - Configuration can be modified safely at runtime
162//! - Log sinks handle concurrent writes from multiple threads
163//! - Async logging uses lock-free queues for producer-consumer pattern
164//!
165//! ## Usage Example
166//!
167//! ```c
168//! // Create log configuration
169//! DMSCLogConfig* config = dmsc_log_config_new();
170//! if (config == NULL) {
171//!     fprintf(stderr, "Failed to create log config\n");
172//!     return ERROR_INIT;
173//! }
174//!
175//! // Configure logging
176//! dmsc_log_config_set_level(config, LOG_LEVEL_DEBUG);
177//! dmsc_log_config_set_format(config, "[%t] %l: %m");
178//! dmsc_log_config_set_console_sink(config, true);
179//!
180//! // Enable file logging with rotation
181//! dmsc_log_config_set_file_sink(config, "/var/log/app.log", 10485760, 5);
182//!
183//! // Create logger instance
184//! DMSCLogger* logger = dmsc_logger_new(config);
185//! if (logger == NULL) {
186//!     fprintf(stderr, "Failed to create logger\n");
187//!     dmsc_log_config_free(config);
188//!     return ERROR_INIT;
189//! }
190//!
191//! // Log messages at different levels
192//! dmsc_log_trace(logger, "Entering function calculate_metrics");
193//! dmsc_log_debug(logger, "Processing request %d for user %s", request_id, username);
194//! dmsc_log_info(logger, "User %s logged in successfully", username);
195//! dmsc_log_warn(logger, "Rate limit approaching threshold: %d/%d", current, max);
196//! dmsc_log_error(logger, "Failed to connect to database: %s", error_message);
197//! dmsc_log_fatal(logger, "Critical failure in payment processing");
198//!
199//! // Structured logging with fields
200//! DMSCHookContext* fields = dmsc_hook_context_create();
201//! dmsc_hook_context_set_string(fields, "user_id", "12345");
202//! dmsc_hook_context_set_int(fields, "request_duration_ms", 150);
203//! dmsc_hook_context_set_string(fields, "endpoint", "/api/users");
204//!
205//! dmsc_log_with_fields(logger, LOG_LEVEL_INFO, "Request completed", fields);
206//! dmsc_hook_context_free(fields);
207//!
208//! // Change log level at runtime
209//! dmsc_logger_set_level(logger, LOG_LEVEL_INFO);
210//!
211//! // Flush pending logs
212//! dmsc_logger_flush(logger);
213//!
214//! // Cleanup
215//! dmsc_logger_free(logger);
216//! dmsc_log_config_free(config);
217//! ```
218//!
219//! ## Dependencies
220//!
221//! This module depends on the following DMSC components:
222//!
223//! - `crate::log`: Rust logging module implementation
224//! - `crate::prelude`: Common types and traits
225//! - time for timestamp formatting
226//!
227//! ## Feature Flags
228//!
229//! The logging module is always enabled as it provides fundamental observability
230//! infrastructure for DMSC applications.
231//!
232//! Additional sinks enabled by feature flags:
233//!
234//! - `log-syslog`: Enable syslog sink (Unix only)
235//! - `log-journald`: Enable journald sink (systemd systems)
236//! - `log-network`: Enable network sink for remote logging
237
238use crate::log::{DMSCLogConfig, DMSCLogger};
239
240
241c_wrapper!(CDMSCLogConfig, DMSCLogConfig);
242c_wrapper!(CDMSCLogger, DMSCLogger);
243
244// DMSCLogConfig constructors and destructors
245c_constructor!(
246    dmsc_log_config_new,
247    CDMSCLogConfig,
248    DMSCLogConfig,
249    DMSCLogConfig::default()
250);
251c_destructor!(dmsc_log_config_free, CDMSCLogConfig);