logfusion 0.1.0

Unified logging and error handling for Rust with structured data, tracing integration, and cross-language support
Documentation
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Enhanced define_errors! macro with structured tracing integration
// This module ONLY contains the define_errors! macro - all logging macros are in tracing.rs
//
// MACRO ORGANIZATION:
// 1. THISERROR COMPATIBILITY - Traditional thiserror enum syntax 
// 2. LOGFUSION SYNTAX - Simplified error definition with attributes
// 3. LOGFUSION INTERNAL PROCESSING - Token parsing and variant collection
// 4. ENUM GENERATION - Pattern matching for different variant types
// 5. MIXED VARIANT PROCESSING - Handling unit + struct variants together  
// 6. LOGGING HELPERS - Shared utilities + LogFusion & thiserror attribute parsing

/// Enhanced `define_errors!` macro with structured tracing integration.
/// 
/// Supports both thiserror-style and simplified LogFusion-style syntax.
/// See examples in the cookbook folder and comprehensive tests for usage patterns.
#[macro_export]
macro_rules! define_errors {

    // ==================================================================================
    // THISERROR COMPATIBILITY SECTION
    // ==================================================================================
    // Traditional thiserror syntax (must come first to avoid conflicts with LogFusion)
    (
        $(#[$enum_meta:meta])*
        $vis:vis enum $name:ident {
            $(
                #[error($msg:literal $(, level = $level:ident)? $(, target = $target:literal)? $(, source)?)]
                $variant:ident $({
                    $(
                        $(#[$field_meta:meta])*
                        $field_name:ident: $field_type:ty
                    ),* $(,)?
                })?,
            )*
        }
    ) => {
        // Generate thiserror Error enum with source chain support
        #[derive(thiserror::Error, Debug)]
        $(#[$enum_meta])*
        $vis enum $name {
            $(
                #[error($msg)]
                $variant $({
                    $(
                        $(#[$field_meta])*
                        $field_name: $field_type
                    ),*
                })?,
            )*
        }

        impl $name {
            /// Automatically log this error with structured tracing (preserves source chain)
            pub fn log(&self) {
                match self {
                    $(
                        Self::$variant { .. } => {
                            let code = self.code();
                            let message = self.to_string();
                            
                            // Use traditional thiserror attribute parsing
                            define_errors!(@log_thiserror $($level)? $($target)? ; code, message);
                        },
                    )*
                }
            }
            
            /// Get error code for API stability
            /// 
            /// Returns a static string identifier for this error variant.
            /// Useful for programmatic error handling and API responses.
            pub fn code(&self) -> &'static str {
                match self {
                    $(
                        Self::$variant { .. } => stringify!($variant),
                    )*
                }
            }
            
            /// Get structured error information for debugging and metrics
            /// 
            /// Returns a tuple of (code, level, target) for this error variant.
            /// This is useful for error analytics, monitoring, and structured logging.
            /// 
            /// # Returns
            /// - `code`: Static string identifier for the error variant
            /// - `level`: Log level as specified in attributes (defaults to "error")
            /// - `target`: Log target module (defaults to current module)
            pub fn error_info(&self) -> (&'static str, &'static str, &'static str) {
                match self {
                    $(
                        Self::$variant { .. } => {
                            let code = stringify!($variant);
                            // For thiserror format, we extract from thiserror attributes
                            define_errors!(@extract_thiserror_info $($level)? $($target)? ; code)
                        },
                    )*
                }
            }
        }
    };

    // ==================================================================================
    // LOGFUSION SYNTAX SECTION  
    // ==================================================================================

    // Multiple error types in one macro call (must come before single type)
    (
        $first_name:ident {
            $($first_tokens:tt)*
        }
        $($rest_name:ident {
            $($rest_tokens:tt)*
        })+
    ) => {
        // Process the first error type
        define_errors! {
            $first_name {
                $($first_tokens)*
            }
        }
        
        // Process the remaining error types
        define_errors! {
            $($rest_name {
                $($rest_tokens)*
            })+
        }
    };

    // Single error type (mixed variants with mandatory braces)
    (
        $name:ident {
            $($tokens:tt)*
        }
    ) => {
        // Collect all the variant information first
        define_errors!(@collect 
            name: $name,
            variants: [],
            tokens: [$($tokens)*]
        );
    };
    
    // ==================================================================================
    // LOGFUSION INTERNAL PROCESSING PATTERNS
    // ==================================================================================
    
    // Parse LogFusion variant syntax: VariantName { fields... } : "message" [attributes]
    (@collect
        name: $name:ident,
        variants: [$($variants:tt)*],
        tokens: [
            $variant:ident { $($field_name:ident : $field_type:ty),* $(,)? } : $msg:literal $([$($attr:tt)*])? 
            $(, $($rest:tt)*)?
        ]
    ) => {
        define_errors!(@collect
            name: $name,
            variants: [$($variants)*
                ($variant, $msg, ($($field_name : $field_type),*), $([$($attr)*])?)
            ],
            tokens: [$($($rest)*)?]
        );
    };
    
    // All variants collected - dispatch to appropriate enum generator
    (@collect
        name: $name:ident,
        variants: [$($variants:tt)*],
        tokens: []
    ) => {
        define_errors!(@build $name; $($variants)*);
    };
    
    // -----------------------------------------------------------------------------------
    // ENUM GENERATION PATTERNS
    // -----------------------------------------------------------------------------------
    
    // Build the final enum - handle empty and non-empty field cases separately
    (@build $name:ident; $(($variant:ident, $msg:literal, (), $([$($attr:tt)*])?))*) => {
        // All unit variants (no fields)
        #[derive(thiserror::Error, Debug)]
        pub enum $name {
            $(
                #[error($msg)]
                $variant,
            )*
        }

        impl $name {
            pub fn log(&self) {
                match self {
                    $(
                        Self::$variant => {
                            let code = self.code();
                            let message = self.to_string();
                            define_errors!(@log_simple $([$($attr)*])? ; code, message);
                        },
                    )*
                }
            }
            
            /// Get error code for API stability
            /// 
            /// Returns a static string identifier for this error variant.
            pub fn code(&self) -> &'static str {
                match self {
                    $(
                        Self::$variant => stringify!($variant),
                    )*
                }
            }
            
            /// Get structured error information for debugging and metrics
            /// 
            /// Returns a tuple of (code, level, target) for this error variant.
            /// 
            /// # Returns
            /// - `code`: Static string identifier for the error variant
            /// - `level`: Log level as specified in attributes (defaults to "error")
            /// - `target`: Log target module (defaults to current module)
            pub fn error_info(&self) -> (&'static str, &'static str, &'static str) {
                match self {
                    $(
                        Self::$variant => {
                            let code = stringify!($variant);
                            define_errors!(@extract_info $([$($attr)*])? ; code)
                        },
                    )*
                }
            }
        }
    };

    (@build $name:ident; $(($variant:ident, $msg:literal, ($($field_name:ident : $field_type:ty),+), $([$($attr:tt)*])?))*) => {
        // All struct variants (with fields)
        #[derive(thiserror::Error, Debug)]
        pub enum $name {
            $(
                #[error($msg)]
                $variant {
                    $($field_name : $field_type),+
                },
            )*
        }

        impl $name {
            pub fn log(&self) {
                match self {
                    $(
                        Self::$variant { .. } => {
                            let code = self.code();
                            let message = self.to_string();
                            define_errors!(@log_simple $([$($attr)*])? ; code, message);
                        },
                    )*
                }
            }
            
            /// Get error code for API stability
            /// 
            /// Returns a static string identifier for this error variant.
            pub fn code(&self) -> &'static str {
                match self {
                    $(
                        Self::$variant { .. } => stringify!($variant),
                    )*
                }
            }
            
            /// Get structured error information for debugging and metrics
            /// 
            /// Returns a tuple of (code, level, target) for this error variant.
            /// 
            /// # Returns
            /// - `code`: Static string identifier for the error variant
            /// - `level`: Log level as specified in attributes (defaults to "error")
            /// - `target`: Log target module (defaults to current module)
            pub fn error_info(&self) -> (&'static str, &'static str, &'static str) {
                match self {
                    $(
                        Self::$variant { .. } => {
                            let code = stringify!($variant);
                            define_errors!(@extract_info $([$($attr)*])? ; code)
                        },
                    )*
                }
            }
        }
    };

    // -----------------------------------------------------------------------------------
    // MIXED VARIANT PROCESSING (Unit + Struct variants in same enum)
    // -----------------------------------------------------------------------------------
    
    // Mixed variants (some unit, some struct) - requires separation and special handling
    (@build $name:ident; $(($variant:ident, $msg:literal, ($($field_name:ident : $field_type:ty),*), $([$($attr:tt)*])?))*) => {
        // For truly mixed variants, we need to pre-process to separate unit from struct
        define_errors!(@separate_mixed $name; 
            unit_variants: [];
            struct_variants: [];
            remaining: [$(($variant, $msg, ($($field_name : $field_type),*), $([$($attr)*])?))*]
        );
    };

    // Sort variants into unit (no fields) and struct (with fields) categories
    (@separate_mixed $name:ident;
        unit_variants: [$($unit_processed:tt)*];
        struct_variants: [$($struct_processed:tt)*];
        remaining: [($variant:ident, $msg:literal, (), $([$($attr:tt)*])?) $($rest:tt)*]
    ) => {
        // Empty fields () = unit variant
        define_errors!(@separate_mixed $name;
            unit_variants: [$($unit_processed)* ($variant, $msg, $([$($attr)*])?)];
            struct_variants: [$($struct_processed)*];
            remaining: [$($rest)*]
        );
    };

    (@separate_mixed $name:ident;
        unit_variants: [$($unit_processed:tt)*];
        struct_variants: [$($struct_processed:tt)*];
        remaining: [($variant:ident, $msg:literal, ($($field_name:ident : $field_type:ty),+), $([$($attr:tt)*])?) $($rest:tt)*]
    ) => {
        // Has fields = struct variant
        define_errors!(@separate_mixed $name;
            unit_variants: [$($unit_processed)*];
            struct_variants: [$($struct_processed)* ($variant, $msg, ($($field_name : $field_type),+), $([$($attr)*])?)];
            remaining: [$($rest)*]
        );
    };

    // Generate final enum with both unit and struct variants
    (@separate_mixed $name:ident;
        unit_variants: [$(($unit_variant:ident, $unit_msg:literal, $([$($unit_attr:tt)*])?))*];
        struct_variants: [$(($struct_variant:ident, $struct_msg:literal, ($($struct_field_name:ident : $struct_field_type:ty),+), $([$($struct_attr:tt)*])?))*];
        remaining: []
    ) => {
        #[derive(thiserror::Error, Debug)]
        pub enum $name {
            $(
                #[error($unit_msg)]
                $unit_variant,
            )*
            $(
                #[error($struct_msg)]
                $struct_variant {
                    $($struct_field_name : $struct_field_type),+
                },
            )*
        }

        impl $name {
            pub fn log(&self) {
                match self {
                    $(
                        Self::$unit_variant => {
                            let code = self.code();
                            let message = self.to_string();
                            define_errors!(@log_simple $([$($unit_attr)*])? ; code, message);
                        },
                    )*
                    $(
                        Self::$struct_variant { .. } => {
                            let code = self.code();
                            let message = self.to_string();
                            define_errors!(@log_simple $([$($struct_attr)*])? ; code, message);
                        },
                    )*
                }
            }
            
            /// Get error code for API stability
            /// 
            /// Returns a static string identifier for this error variant.
            pub fn code(&self) -> &'static str {
                match self {
                    $(
                        Self::$unit_variant => stringify!($unit_variant),
                    )*
                    $(
                        Self::$struct_variant { .. } => stringify!($struct_variant),
                    )*
                }
            }
            
            /// Get structured error information for debugging and metrics
            /// 
            /// Returns a tuple of (code, level, target) for this error variant.
            /// 
            /// # Returns
            /// - `code`: Static string identifier for the error variant
            /// - `level`: Log level as specified in attributes (defaults to "error")
            /// - `target`: Log target module (defaults to current module)
            pub fn error_info(&self) -> (&'static str, &'static str, &'static str) {
                match self {
                    $(
                        Self::$unit_variant => {
                            let code = stringify!($unit_variant);
                            define_errors!(@extract_info $([$($unit_attr)*])? ; code)
                        },
                    )*
                    $(
                        Self::$struct_variant { .. } => {
                            let code = stringify!($struct_variant);
                            define_errors!(@extract_info $([$($struct_attr)*])? ; code)
                        },
                    )*
                }
            }
        }
    };

    // ==================================================================================
    // LOGGING HELPER PATTERNS
    // ==================================================================================
    
    // -----------------------------------------------------------------------------------
    // SHARED LOGGING UTILITIES (used by both thiserror and LogFusion)
    // -----------------------------------------------------------------------------------
    
    // Simple logging dispatcher - routes to appropriate attribute parser
    (@log_simple [$($attr:tt)*] ; $code:expr, $message:expr) => {
        define_errors!(@log_with_attrs $($attr)* ; $code, $message);
    };
    
    (@log_simple ; $code:expr, $message:expr) => {
        $crate::error!(target: module_path!(), "[{}] {}", $code, $message);
    };

    // -----------------------------------------------------------------------------------
    // LOGFUSION ATTRIBUTE PARSING (level = X, target = Y syntax)
    // -----------------------------------------------------------------------------------
    (@log_with_attrs level = error, target = $target:literal ; $code:expr, $message:expr) => {
        $crate::error!(target: $target, "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = warn, target = $target:literal ; $code:expr, $message:expr) => {
        $crate::warn!(target: $target, "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = info, target = $target:literal ; $code:expr, $message:expr) => {
        $crate::info!(target: $target, "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = debug, target = $target:literal ; $code:expr, $message:expr) => {
        $crate::debug!(target: $target, "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = trace, target = $target:literal ; $code:expr, $message:expr) => {
        $crate::trace!(target: $target, "[{}] {}", $code, $message);
    };
    
    // Log level only (default target)
    (@log_with_attrs level = error ; $code:expr, $message:expr) => {
        $crate::error!(target: module_path!(), "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = warn ; $code:expr, $message:expr) => {
        $crate::warn!(target: module_path!(), "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = info ; $code:expr, $message:expr) => {
        $crate::info!(target: module_path!(), "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = debug ; $code:expr, $message:expr) => {
        $crate::debug!(target: module_path!(), "[{}] {}", $code, $message);
    };
    (@log_with_attrs level = trace ; $code:expr, $message:expr) => {
        $crate::trace!(target: module_path!(), "[{}] {}", $code, $message);
    };
    
    // Target only (default level = error)  
    (@log_with_attrs target = $target:literal ; $code:expr, $message:expr) => {
        $crate::error!(target: $target, "[{}] {}", $code, $message);
    };
    
    // Neither level nor target (both defaults)
    (@log_with_attrs ; $code:expr, $message:expr) => {
        $crate::error!(target: module_path!(), "[{}] {}", $code, $message);
    };
    
    // -----------------------------------------------------------------------------------
    // THISERROR ATTRIBUTE PARSING (compatibility layer)
    // -----------------------------------------------------------------------------------
    // These delegate to @log_with_attrs but handle thiserror's different syntax
    (@log_thiserror $level:ident $target:literal ; $code:expr, $message:expr) => {
        define_errors!(@log_with_attrs level = $level, target = $target ; $code, $message);
    };
    (@log_thiserror $level:ident ; $code:expr, $message:expr) => {
        define_errors!(@log_with_attrs level = $level ; $code, $message);
    };
    (@log_thiserror $target:literal ; $code:expr, $message:expr) => {
        define_errors!(@log_with_attrs target = $target ; $code, $message);
    };
    (@log_thiserror ; $code:expr, $message:expr) => {
        define_errors!(@log_with_attrs ; $code, $message);
    };

    // -----------------------------------------------------------------------------------
    // STRUCTURED ERROR INFO EXTRACTION
    // -----------------------------------------------------------------------------------
    // For thiserror format - different attribute parsing
    (@extract_thiserror_info $level:ident $target:literal ; $code:expr) => {
        ($code, stringify!($level), $target)
    };
    (@extract_thiserror_info $level:ident ; $code:expr) => {
        ($code, stringify!($level), module_path!())
    };
    (@extract_thiserror_info $target:literal ; $code:expr) => {
        ($code, "error", $target)
    };
    (@extract_thiserror_info ; $code:expr) => {
        ($code, "error", module_path!())
    };
    
    // For LogFusion format - bracket-based attributes
    (@extract_info [level = $level:ident, target = $target:literal] ; $code:expr) => {
        ($code, stringify!($level), $target)
    };
    (@extract_info [target = $target:literal, level = $level:ident] ; $code:expr) => {
        ($code, stringify!($level), $target)
    };
    (@extract_info [level = $level:ident] ; $code:expr) => {
        ($code, stringify!($level), module_path!())
    };
    (@extract_info [target = $target:literal] ; $code:expr) => {
        ($code, "error", $target)
    };
    (@extract_info ; $code:expr) => {
        ($code, "error", module_path!())
    };

}