1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Core logger trait and infrastructure for the logwise logging system.
//!
//! This module defines the fundamental [`Logger`] trait that all logging backends must implement.
//! The trait provides a simple yet flexible interface for processing log records, supporting both
//! synchronous and asynchronous logging patterns.
//!
//! # Architecture
//!
//! The `Logger` trait is the core abstraction that enables logwise to support multiple logging
//! backends simultaneously. Each logger implementation receives [`LogRecord`] instances containing
//! the formatted log data and is responsible for outputting them to its destination (stderr, files,
//! network, memory, etc.).
//!
//! ## Design Principles
//!
//! - **Simplicity**: The trait has only three required methods, making it easy to implement custom loggers
//! - **Flexibility**: Supports both sync and async logging patterns for different runtime environments
//! - **Thread Safety**: All loggers must be `Send + Sync` to work in multi-threaded environments
//! - **Zero Allocation**: The [`LogRecord`] is passed by value to avoid unnecessary allocations
//! - **Graceful Shutdown**: The `prepare_to_die` method ensures buffers are flushed before exit
//!
//! # Built-in Implementations
//!
//! logwise provides several logger implementations:
//!
//! - [`StdErrorLogger`](crate::StdErrorLogger): Outputs to stderr (default logger)
//! - [`InMemoryLogger`](crate::InMemoryLogger): Stores logs in memory for testing
//! - [`LocalLogger`](crate::local_logger::LocalLogger): Thread-local logging for performance
//!
//! # Custom Logger Implementation
//!
//! To create a custom logger, implement the `Logger` trait:
//!
//! ```
//! use logwise::{Logger, LogRecord};
//! use std::sync::Mutex;
//!
//! #[derive(Debug)]
//! struct FileLogger {
//! file: Mutex<std::fs::File>,
//! }
//!
//! impl FileLogger {
//! fn new(path: &str) -> std::io::Result<Self> {
//! use std::fs::OpenOptions;
//! let file = OpenOptions::new()
//! .create(true)
//! .append(true)
//! .open(path)?;
//! Ok(Self {
//! file: Mutex::new(file),
//! })
//! }
//! }
//!
//! impl Logger for FileLogger {
//! fn finish_log_record(&self, record: LogRecord) {
//! use std::io::Write;
//! let mut file = self.file.lock().unwrap();
//! writeln!(file, "{}", record).ok();
//! }
//!
//! fn finish_log_record_async<'s>(
//! &'s self,
//! record: LogRecord,
//! ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 's>> {
//! // Simple async wrapper around sync implementation
//! Box::pin(async move {
//! self.finish_log_record(record);
//! })
//! }
//!
//! fn prepare_to_die(&self) {
//! use std::io::Write;
//! let mut file = self.file.lock().unwrap();
//! file.flush().ok();
//! }
//! }
//! ```
//!
//! # Global Logger Management
//!
//! Loggers are typically registered globally using the [`global_logger`](crate::global_logger) module:
//!
//! ```
//! logwise::declare_logging_domain!();
//! # fn main() {
//! use logwise::{Logger, add_global_logger};
//! use std::sync::Arc;
//!
//! # #[derive(Debug)]
//! # struct MyCustomLogger;
//! # impl Logger for MyCustomLogger {
//! # fn finish_log_record(&self, _: logwise::LogRecord) {}
//! # fn finish_log_record_async<'s>(&'s self, record: logwise::LogRecord)
//! # -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 's>> {
//! # Box::pin(async move { self.finish_log_record(record) })
//! # }
//! # fn prepare_to_die(&self) {}
//! # }
//!
//! // Create and register a custom logger
//! let logger = Arc::new(MyCustomLogger);
//! add_global_logger(logger);
//!
//! // Now all log messages will also go to MyCustomLogger
//! logwise::info_sync!("This message goes to all registered loggers");
//! # }
//! ```
//!
//! # Performance Considerations
//!
//! - The `finish_log_record` method should be fast as it may be called frequently
//! - Consider buffering writes in your logger implementation for better performance
//! - Use the async variant when in async contexts to avoid blocking the executor
//! - The `prepare_to_die` method is called rarely, so it can do more expensive cleanup
//!
//! # Thread Safety
//!
//! All `Logger` implementations must be thread-safe (`Send + Sync`). This typically means:
//! - Using `Mutex` or `RwLock` for mutable state
//! - Using atomic types for simple counters
//! - Ensuring any file handles or network connections are properly synchronized
use crateLogRecord;
use Debug;
/// Core trait for implementing logging backends in logwise.
///
/// This trait defines the interface that all loggers must implement to receive and process
/// log records from the logwise logging system. Implementations can output logs to any
/// destination: stderr, files, network services, or in-memory buffers.
///
/// # Requirements
///
/// All implementations must be:
/// - **Thread-safe**: The logger will be called from multiple threads simultaneously
/// - **Send + Sync**: Required for use in multi-threaded environments
/// - **Debug**: For diagnostic purposes and error reporting
///
/// # Example Implementation
///
/// ```
/// use logwise::{Logger, LogRecord};
/// use std::sync::atomic::{AtomicUsize, Ordering};
///
/// #[derive(Debug)]
/// struct CountingLogger {
/// count: AtomicUsize,
/// }
///
/// impl CountingLogger {
/// fn new() -> Self {
/// Self {
/// count: AtomicUsize::new(0),
/// }
/// }
///
/// fn get_count(&self) -> usize {
/// self.count.load(Ordering::Relaxed)
/// }
/// }
///
/// impl Logger for CountingLogger {
/// fn finish_log_record(&self, _record: LogRecord) {
/// self.count.fetch_add(1, Ordering::Relaxed);
/// // In a real implementation, you would process the record here
/// }
///
/// fn finish_log_record_async<'s>(
/// &'s self,
/// record: LogRecord,
/// ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 's>> {
/// Box::pin(async move {
/// self.finish_log_record(record);
/// })
/// }
///
/// fn prepare_to_die(&self) {
/// // No cleanup needed for this simple logger
/// }
/// }
///
/// // Usage
/// let logger = CountingLogger::new();
/// let mut record = LogRecord::new(logwise::Level::Info);
/// record.log("Test message");
/// logger.finish_log_record(record);
/// assert_eq!(logger.get_count(), 1);
/// ```
// Implementation notes:
//
// The Logger trait intentionally does not implement Clone, as loggers often hold unique
// resources (file handles, network connections) that shouldn't be duplicated.
//
// PartialEq/Eq are not implemented because equality semantics for loggers are unclear
// (do we compare configuration, destination, or identity?).
//
// Default is not implemented as loggers typically require configuration (output paths,
// network endpoints, etc.) that cannot be reasonably defaulted.
//
// Send + Sync are required to enable multi-threaded logging, which is essential for
// most Rust applications. Loggers that cannot be made thread-safe should not be used
// with logwise.