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
# LogFusion

[![Crates.io](https://img.shields.io/crates/v/logfusion.svg)](https://crates.io/crates/logfusion)
[![Documentation](https://docs.rs/logfusion/badge.svg)](https://docs.rs/logfusion)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Tracing-native logging macros with structured logging support and enhanced error handling for Rust.**

LogFusion provides a clean, modern logging interface built on top of the `tracing` ecosystem, offering structured logging, automatic initialization, and powerful error handling capabilities.

## โœจ Key Features

- **๐ŸŽฏ Tracing-Native** - Built on the modern `tracing` ecosystem for superior observability
- **๐Ÿ“Š Structured Logging** - First-class support for structured fields and metadata
- **๐Ÿ”„ Auto-Initialization** - Automatic tracing subscriber setup with smart defaults
- **๐ŸŒ‰ Log Crate Bridge** - Seamless compatibility with libraries using the `log` crate
- **๐Ÿ”— FFI Callback Support** - Optional integration with Python, Node.js, C/C++, and WebAssembly
- **โšก Enhanced Error Handling** - Dual-syntax `define_errors!` macro with LogFusion format + thiserror compatibility
- **๐Ÿ› ๏ธ Zero Config** - Works out of the box with sensible defaults
- **๐Ÿ”ง Spans & Instrumentation** - Full support for tracing spans and `#[instrument]`

## ๐Ÿš€ Quick Start

### Add LogFusion to your project

```toml
[dependencies]
logfusion = "0.2"

# Optional: Add tracing-subscriber for advanced configuration
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
```

### Basic Usage

```rust
use logfusion::{info, warn, error, debug, trace};

fn main() {
    // LogFusion auto-initializes tracing - no setup needed!
    
    info!("Application starting");
    warn!("This is a warning");
    error!("Something went wrong");
    
    // Structured logging with fields
    info!(
        user_id = 12345,
        action = "login",
        ip_address = "192.168.1.1",
        duration_ms = 145,
        "User authentication successful"
    );
}
```

### Enhanced Error Handling

**New LogFusion Format** (Simplified & Powerful):

```rust
use logfusion::define_errors;

// ๐Ÿ†• LogFusion Format - Clean, attribute-based syntax
define_errors! {
    AppError {
        DatabaseConnection { host: String, port: u16 } : "Database connection failed: {host}:{port}" [level = error, target = "app::db"],
        UserNotFound { user_id: u64 } : "User not found: {user_id}" [level = warn],
        InvalidConfig {} : "Invalid configuration detected" [level = error],
        NetworkTimeout { source: std::io::Error } : "Network operation timed out"  // Auto source chaining
    }
}

// Multiple error types in one macro
define_errors! {
    ApiError {
        BadRequest { field: String } : "Invalid field: {field}" [level = warn],
        Unauthorized {} : "Access denied" [level = error]
    }
    
    DatabaseError {
        ConnectionFailed { host: String } : "Failed to connect to {host}" [level = error]
    }
}

fn example() -> Result<(), AppError> {
    // Errors are automatically logged with structured tracing
    let err = AppError::UserNotFound { user_id: 12345 };
    err.log(); // Logs: WARN app::module: [UserNotFound] User not found: 12345
    
    // ๐Ÿ†• New in v0.2: Error introspection for monitoring & debugging
    let (code, level, target) = err.error_info();
    println!("Code: {}, Level: {}, Target: {}", code, level, target);
    // Output: Code: UserNotFound, Level: warn, Target: app::module
    
    Err(err)
}
```

**Traditional Thiserror Syntax** (Fully Compatible):

```rust
define_errors! {
    pub enum AppError {
        #[error("Database connection failed: {host}:{port}", level = error, target = "app::db")]
        DatabaseConnection { host: String, port: u16 },
        
        #[error("User not found: {user_id}", level = warn)]
        UserNotFound { user_id: u64 },
    }
}
```

### ๐Ÿ” Error Introspection & Monitoring

**New in v0.2**: All generated error enums include an `error_info()` method for monitoring and debugging:

```rust
use logfusion::define_errors;
use std::collections::HashMap;

define_errors! {
    ApiError {
        DatabaseTimeout { query: String } : "Query timed out: {query}" [level = error, target = "db::query"],
        RateLimited {} : "API rate limit exceeded" [level = warn, target = "api::rate"],
        UserNotFound { user_id: u64 } : "User {user_id} not found" [level = info]
    }
}

fn main() {
    let error = ApiError::DatabaseTimeout { query: "SELECT * FROM users".to_string() };
    
    // Get structured error information
    let (code, level, target) = error.error_info();
    println!("Error Code: {}", code);     // "DatabaseTimeout"
    println!("Log Level: {}", level);     // "error" 
    println!("Target: {}", target);       // "db::query"
    
    // Perfect for metrics collection
    let mut error_metrics = HashMap::new();
    *error_metrics.entry(code).or_insert(0) += 1;
    
    // Ideal for monitoring dashboards
    match level {
        "error" => send_alert_to_pagerduty(&error),
        "warn" => increment_warning_counter(),
        _ => log_for_debugging(&error)
    }
}
```

**Use Cases for `error_info()`:**

- ๐Ÿ“Š **Metrics Collection** - Build error dashboards and SLA monitoring
- ๐Ÿšจ **Alerting Systems** - Set up automated alerts based on error patterns
- ๐Ÿ” **Debugging Tools** - Analyze error patterns in production
- ๐Ÿ“ˆ **Business Intelligence** - Track error rates by component/severity

## ๐ŸŽฏ Why LogFusion?

### ๐Ÿ†• Dual-Syntax Error Handling

LogFusion v0.2 introduces a **revolutionary dual-syntax approach** to error definitions:

**LogFusion Format Benefits:**

- โœ… **Cleaner Syntax** - No repetitive `#[error(...)]` attributes
- โœ… **Attribute-Based Logging** - `[level = warn, target = "app::db"]` syntax
- โœ… **Multiple Types** - Define multiple error enums in one macro call
- โœ… **Auto Source Detection** - Fields named `source` automatically become `#[source]`
- โœ… **Mixed Variants** - Unit (`{}`) and struct variants in same enum
- โœ… **Field Interpolation** - `"Failed to connect to {host}:{port}"` syntax

**Performance & Maintainability:**

- ๐Ÿš€ **64% Macro Optimization** - Reduced from 998 to 358 lines while adding features
- ๐Ÿงน **11 Comprehensive Tests** - Every scenario covered with battle-tested reliability
- ๐Ÿ”„ **Full Backward Compatibility** - Existing thiserror syntax continues to work
- ๐Ÿ“Š **Structured Logging Integration** - Seamless tracing ecosystem integration

### Modern Tracing Ecosystem

Built on `tracing`, the modern standard for Rust observability:

- **Structured logging** - Attach key-value metadata to log events
- **Spans** - Track operations across async boundaries
- **Instrumentation** - Automatic span creation with `#[instrument]`
- **Rich ecosystem** - Compatible with OpenTelemetry, Jaeger, Datadog, and more

### Auto-Initialization

No boilerplate setup required:

```rust
use logfusion::info;

fn main() {
    // This works immediately - no initialization needed!
    info!("Hello, world!");
}
```

### Structured Logging Made Easy

```rust
use logfusion::info;

// Rich, structured metadata
info!(
    request_id = "req-123",
    user_id = 12345,
    method = "POST", 
    path = "/api/users",
    status_code = 201,
    duration_ms = 45,
    "API request completed"
);
```

### Backward Compatibility

Works seamlessly with existing `log` crate usage:

```rust
// These both work and are captured by LogFusion
log::info!("Legacy log message");
logfusion::info!("Modern LogFusion message");
```

## ๐Ÿ“Š Structured Logging

LogFusion excels at structured logging, making your logs machine-readable and perfect for modern observability platforms:

```rust
use logfusion::{info, error, info_span};

// User authentication
info!(
    user_id = 12345,
    username = "alice",
    ip_address = "192.168.1.100",
    mfa_enabled = true,
    "User login successful"
);

// Payment processing
error!(
    transaction_id = "txn-abc-123",
    amount_cents = 2999,
    currency = "USD",
    decline_reason = "insufficient_funds",
    "Payment failed"
);

// Spans with structured context
let span = info_span!("process_order", order_id = "order-123", customer_id = 456);
let _enter = span.enter();

info!("Processing order");
info!("Order completed successfully");
```

## ๐Ÿ—๏ธ Spans and Instrumentation

Full support for tracing spans and automatic instrumentation:

```rust
use logfusion::{info, info_span};
use tracing::instrument;

#[instrument(level = "info")]
async fn process_user_request(user_id: u64, action: &str) -> Result<String, AppError> {
    info!("Processing user request");
    
    // Nested spans
    let span = info_span!("database_query", table = "users");
    let _enter = span.enter();
    
    info!("Executing database query");
    
    Ok("Success".to_string())
}
```

## ๐ŸŽ›๏ธ Configuration

### Environment Variables

LogFusion respects standard tracing environment variables:

```bash
# Set log level
RUST_LOG=debug cargo run

# Target specific modules  
RUST_LOG=myapp::database=debug,myapp::auth=info cargo run

# Filter by span names
RUST_LOG=process_order=trace cargo run
```

### Custom Initialization

For advanced use cases, you can configure tracing manually:

```rust
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

fn main() {
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().json())
        .with(tracing_subscriber::EnvFilter::from_default_env())
        .init();
        
    // Now use LogFusion normally
    logfusion::info!("Application started with custom config");
}
```

## ๐Ÿ“š Documentation & Examples

- **[API Documentation]https://docs.rs/logfusion** - Full API reference
- **[Cookbook]cookbook/** - Real-world patterns and best practices
- **[Examples]examples/** - Runnable example code

### Key Examples

- **[`logfusion_format_showcase.rs`]examples/logfusion_format_showcase.rs** - Complete LogFusion format demonstration with all features
- **[`logfusion_source_chaining.rs`]examples/logfusion_source_chaining.rs** - Automatic source chaining with fields named "source"
- **[`field_interpolation_demo.rs`]examples/field_interpolation_demo.rs** - Dual-syntax field interpolation comparison
- **[`structured_logging_demo.rs`]examples/structured_logging_demo.rs** - Manual + automatic structured logging
- **[`advanced_tracing_features.rs`]examples/advanced_tracing_features.rs** - Spans, instrumentation, and ecosystem integration

## ๐ŸŒ‰ FFI and Callback Support

LogFusion includes optional FFI callback support for integrating with other languages:

```toml
[dependencies]
logfusion = { version = "0.2", features = ["callback"] }
```

With the `callback` feature enabled, LogFusion can route log messages to external callbacks, enabling integration with:

- **Python** (via PyO3)
- **Node.js** (via Neon)
- **C/C++** applications
- **WebAssembly** modules
- **Any FFI-compatible language**

```rust
use logfusion::{info, error};

fn main() {
    // These messages are sent to both tracing AND any registered callbacks
    info!("This goes to tracing and FFI callbacks");
    error!("Error messages are bridged to external systems");
}
```

The callback system allows external applications to receive structured log data while LogFusion continues to work normally with the tracing ecosystem.

## ๐Ÿ”ง Feature Flags

LogFusion uses minimal feature flags:

```toml
[dependencies]
logfusion = { version = "0.2", features = ["callback"] }
```

- **`callback`** - Enable FFI callback support (optional, for cross-language integrations)

## ๐ŸŒŸ Use Cases

### Perfect for:

- โœ… **Modern Rust applications** wanting structured observability
- โœ… **Microservices** needing rich context and tracing
- โœ… **Cross-language projects** requiring log bridging to Python, Node.js, or C/C++
- โœ… **Rust libraries** embedded in other language ecosystems
- โœ… **Applications** migrating from `log` to `tracing`
- โœ… **Projects** needing automatic error logging with proper types

### Consider alternatives if:

- โŒ You just need basic text logging (use `log` + `env_logger`)
- โŒ You're happy with your current logging setup
- โŒ You don't need structured logging or error handling

## ๐Ÿค Ecosystem Compatibility

LogFusion works seamlessly with the entire tracing ecosystem:

- **[`tracing-subscriber`]https://docs.rs/tracing-subscriber** - Flexible subscriber implementations
- **[`tracing-opentelemetry`]https://docs.rs/tracing-opentelemetry** - OpenTelemetry integration
- **[`console-subscriber`]https://docs.rs/console-subscriber** - Tokio Console integration
- **[`tracing-appender`]https://docs.rs/tracing-appender** - File output and rotation
- **[`tracing-flame`]https://docs.rs/tracing-flame** - Flamegraph profiling

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

Built on top of the excellent [`tracing`](https://docs.rs/tracing) and [`thiserror`](https://docs.rs/thiserror) crates. Special thanks to the Rust logging ecosystem maintainers.