kerf 0.1.2

Simple tokio-based trace event collector
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
use anyhow::Result;
use kerf::{Config, EventType, Kerf, Level, Match, MatcherSet, StatsConfig};
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;

// Command to log messages or manage log files
struct LogMessage {
    destination: String,
    message: Arc<kerf::Event>,
}

// Enhanced logger that tracks stats
struct StatsLogger {
    file_loggers: std::collections::HashMap<String, Arc<Mutex<File>>>,
    log_counts: std::collections::HashMap<String, usize>,
}

impl StatsLogger {
    fn new(log_dir: PathBuf) -> io::Result<Self> {
        std::fs::create_dir_all(&log_dir)?;

        let mut file_loggers = std::collections::HashMap::new();
        let mut log_counts = std::collections::HashMap::new();

        // Initialize file loggers for different categories
        for dest in ["captured", "silenced", "dropped"] {
            let file_path = log_dir.join(format!("{dest}.log"));
            let file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&file_path)?;

            file_loggers.insert(dest.to_string(), Arc::new(Mutex::new(file)));
            log_counts.insert(dest.to_string(), 0);
        }

        // Initialize count for stdout
        log_counts.insert("stdout".to_string(), 0);

        Ok(Self {
            file_loggers,
            log_counts,
        })
    }

    fn log_message(&mut self, destination: &str, event: Arc<kerf::Event>) -> io::Result<()> {
        let formatted = format!(
            "[{}] {} - {}\n",
            event.level,
            event.module_path.as_deref().unwrap_or("unknown"),
            event.message
        );

        match destination {
            "stdout" => {
                print!("CAPTURED: {formatted}");
                *self.log_counts.entry("stdout".to_string()).or_insert(0) += 1;
            }
            _ => {
                if let Some(file_lock) = self.file_loggers.get(destination) {
                    let mut file = file_lock.lock().unwrap();
                    file.write_all(formatted.as_bytes())?;
                    file.flush()?;
                    *self.log_counts.entry(destination.to_string()).or_insert(0) += 1;
                } else {
                    return Err(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No logger for destination: {destination}"),
                    ));
                }
            }
        }

        Ok(())
    }

    fn print_summary(&self) {
        println!("\n=== LOGGER SUMMARY ===");
        for (dest, count) in &self.log_counts {
            println!("{dest}: {count} events");
        }
        println!("=======================\n");
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    // Create a temporary directory for log files
    let log_dir = tempfile::tempdir()?.keep();
    println!("=== KERF STATISTICS DEMONSTRATION ===");
    println!("Log directory: {}", log_dir.display());
    println!("======================================\n");

    // Enable comprehensive stats tracking
    let stats_config = StatsConfig {
        track_by_location: true,
        track_by_module: true,
        track_by_level: true,
        max_locations: 1000,
        max_modules: 100,
    };

    // Create sophisticated filtering with capture, silence, and drop scenarios
    let mut capture_matcher = MatcherSet::empty();
    capture_matcher.add_matcher(Match::info().module_pattern("demo::*")); // Capture demo module events
    capture_matcher.add_matcher(Match::warn().all_modules()); // Capture all warnings
    capture_matcher.add_matcher(Match::error().all_modules()); // Capture all errors

    let mut silence_matcher = MatcherSet::empty();
    silence_matcher.add_matcher(Match::debug().module_pattern("demo::*")); // Include debug from demo
    silence_matcher.add_matcher(Match::debug().exclude().module_pattern("demo::noisy")); // But silence noisy module

    // Create config with stats enabled
    let config = Config::empty()
        .with_tab("main_capture", capture_matcher)
        .with_tab("debug_with_silence", silence_matcher)
        .with_stats(stats_config);

    // Initialize the tracer
    let tracer = Kerf::init(config)?;

    // Set up event logging
    let (tx, mut rx) = mpsc::unbounded_channel::<LogMessage>();
    let logger = Arc::new(Mutex::new(StatsLogger::new(log_dir.clone())?));

    // Background task to process log messages
    let logger_clone = Arc::clone(&logger);
    tokio::spawn(async move {
        while let Some(LogMessage {
            destination,
            message,
        }) = rx.recv().await
        {
            let mut logger = logger_clone.lock().unwrap();
            if let Err(e) = logger.log_message(&destination, message) {
                eprintln!("Error logging to {destination}: {e}");
            }
        }
    });

    // Set up callbacks to track different event types
    let tx_captured = tx.clone();
    tracer
        .set_callback(move |event, _tab_names| {
            // Log to stdout and captured file
            let _ = tx_captured.send(LogMessage {
                destination: "stdout".to_string(),
                message: Arc::clone(&event),
            });
            let _ = tx_captured.send(LogMessage {
                destination: "captured".to_string(),
                message: Arc::clone(&event),
            });
        })?
        .await??;

    let tx_silenced = tx.clone();
    tracer
        .set_silenced_callback(move |event, silencers| {
            println!(
                "SILENCED by {:?}: [{}] {} - {}",
                silencers,
                event.level,
                event.module_path.as_deref().unwrap_or("unknown"),
                event.message
            );
            let _ = tx_silenced.send(LogMessage {
                destination: "silenced".to_string(),
                message: Arc::clone(&event),
            });
        })?
        .await??;

    let tx_dropped = tx.clone();
    tracer
        .set_dropped_callback(move |event| {
            println!(
                "DROPPED: [{}] {} - {}",
                event.level,
                event.module_path.as_deref().unwrap_or("unknown"),
                event.message
            );
            let _ = tx_dropped.send(LogMessage {
                destination: "dropped".to_string(),
                message: Arc::clone(&event),
            });
        })?
        .await??;

    println!("Starting event generation...\n");

    // Generate events from multiple modules to demonstrate stats
    tokio::spawn(async move {
        // Demo module events (will be captured)
        demo::core::generate_events().await;
        demo::database::generate_events().await;
        demo::network::generate_events().await;
        demo::noisy::generate_events().await; // Debug events will be silenced

        // External module events (will be dropped unless they're warnings/errors)
        external::service::generate_events().await;
        external::utils::generate_events().await;

        // Mixed level events to show stats breakdown
        for i in 0..5 {
            tracing::info!(target: "demo::mixed", "Mixed info event {}", i);
            tracing::warn!(target: "demo::mixed", "Mixed warning event {}", i);
            if i % 2 == 0 {
                tracing::error!(target: "demo::mixed", "Mixed error event {}", i);
            }
            if i % 3 == 0 {
                tracing::debug!(target: "demo::mixed", "Mixed debug event {}", i);
                tracing::trace!(target: "demo::mixed", "Mixed trace event {}", i);
            }
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        }

        println!("\nEvent generation complete!");
    });

    // Wait for events to be processed
    tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;

    // Print comprehensive stats
    print_comprehensive_stats(&tracer).await?;

    // Print logger summary
    let logger = logger.lock().unwrap();
    logger.print_summary();

    println!("Stats demonstration complete!");
    println!("Check log files in: {}", log_dir.display());

    Ok(())
}

async fn print_comprehensive_stats(tracer: &Kerf) -> Result<()> {
    if let Ok(stats_rx) = tracer.get_stats() {
        if let Ok(Some(snapshot)) = stats_rx.await {
            println!("\n=== COMPREHENSIVE STATISTICS REPORT ===");
            println!("Total tracked entries: {}", snapshot.total_entries);

            // Overall summary by event type
            println!("\n--- EVENT TYPE SUMMARY ---");
            let mut captured_total = 0;
            let mut silenced_total = 0;
            let mut dropped_total = 0;

            // Use level_event_counts instead of level_stats
            for ((_level, event_type), count) in &snapshot.level_event_counts {
                match event_type {
                    EventType::Captured => captured_total += count,
                    EventType::Silenced => silenced_total += count,
                    EventType::Dropped => dropped_total += count,
                }
            }

            println!("📈 Captured: {captured_total}");
            println!("🔇 Silenced: {silenced_total}");
            println!("🗑️  Dropped:  {dropped_total}");
            println!(
                "📊 Total:    {}",
                captured_total + silenced_total + dropped_total
            );

            // Breakdown by level and event type
            println!("\n--- LEVEL BREAKDOWN ---");
            for level in [
                Level::ERROR,
                Level::WARN,
                Level::INFO,
                Level::DEBUG,
                Level::TRACE,
            ] {
                // Use level_event_counts instead of level_stats
                let captured = snapshot
                    .level_event_counts
                    .get(&(level, EventType::Captured))
                    .unwrap_or(&0);
                let silenced = snapshot
                    .level_event_counts
                    .get(&(level, EventType::Silenced))
                    .unwrap_or(&0);
                let dropped = snapshot
                    .level_event_counts
                    .get(&(level, EventType::Dropped))
                    .unwrap_or(&0);
                let total = captured + silenced + dropped;

                if total > 0 {
                    println!(
                        "{level:5}: {captured:3} captured, {silenced:3} silenced, {dropped:3} dropped (total: {total})"
                    );
                }
            }

            // Module stats
            println!("\n--- MODULE STATISTICS ---");
            let mut modules: Vec<_> = snapshot.module_stats.iter().collect();
            modules.sort_by_key(|(name, _)| name.to_string());

            for (module, stats) in modules {
                let captured = stats.get_total_for_type(EventType::Captured);
                let silenced = stats.get_total_for_type(EventType::Silenced);
                let dropped = stats.get_total_for_type(EventType::Dropped);
                println!(
                    "{module:20}: {captured:3} captured, {silenced:3} silenced, {dropped:3} dropped"
                );
            }

            // Location stats (top 10 most active)
            println!("\n--- TOP ACTIVE LOCATIONS ---");
            let mut locations: Vec<_> = snapshot.location_stats.iter().collect();
            locations.sort_by(|(_, a), (_, b)| {
                let a_total = a.get_total_for_type(EventType::Captured)
                    + a.get_total_for_type(EventType::Silenced)
                    + a.get_total_for_type(EventType::Dropped);
                let b_total = b.get_total_for_type(EventType::Captured)
                    + b.get_total_for_type(EventType::Silenced)
                    + b.get_total_for_type(EventType::Dropped);
                b_total.cmp(&a_total)
            });

            for (location, stats) in locations.iter().take(10) {
                let captured = stats.get_total_for_type(EventType::Captured);
                let silenced = stats.get_total_for_type(EventType::Silenced);
                let dropped = stats.get_total_for_type(EventType::Dropped);
                let total = captured + silenced + dropped;
                if total > 0 {
                    println!("{location:30}: {total:3} total events");
                }
            }

            // Raw stats summary (just counts)
            println!("\n--- RAW STATS SUMMARY ---");
            println!("Raw stat entries: {}", snapshot.raw_stats.len());
            println!("Total counters: {}", snapshot.total_counters.len());

            // Configuration info
            println!("\n--- CONFIGURATION ---");
            println!("Track by location: {}", snapshot.config.track_by_location);
            println!("Track by module:   {}", snapshot.config.track_by_module);
            println!("Track by level:    {}", snapshot.config.track_by_level);
            println!("Max locations:     {}", snapshot.config.max_locations);
            println!("Max modules:       {}", snapshot.config.max_modules);
            println!("Locations tracked: {}", snapshot.location_count);
            println!("Modules tracked:   {}", snapshot.module_count);

            println!("=====================================\n");
        }
    }
    Ok(())
}

// Demo modules that generate different types of events
mod demo {
    pub mod core {
        use tracing::{debug, error, info, trace, warn};

        pub async fn generate_events() {
            info!("Core module initializing");
            debug!("Core debug: loading configuration");
            trace!("Core trace: detailed initialization steps");
            warn!("Core warning: deprecated feature used");
            error!("Core error: failed to load optional plugin");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }

    pub mod database {
        use tracing::{debug, error, info, warn};

        pub async fn generate_events() {
            info!("Database connection established");
            debug!("Database debug: connection pool size = 10");
            warn!("Database warning: slow query detected");
            error!("Database error: connection timeout");
            info!("Database transaction completed");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }

    pub mod network {
        use tracing::{debug, error, info, trace, warn};

        pub async fn generate_events() {
            info!("Network module starting");
            debug!("Network debug: binding to port 8080");
            trace!("Network trace: socket configuration");
            warn!("Network warning: high latency detected");
            error!("Network error: failed to bind port 443");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }

    pub mod noisy {
        use tracing::{debug, info, trace};

        pub async fn generate_events() {
            info!("Noisy module info (should be captured)");
            debug!("Noisy module debug (should be silenced)");
            debug!("Another noisy debug (should be silenced)");
            trace!("Noisy trace (should be dropped - too low level)");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }
}

// External modules (events should mostly be dropped unless they're warnings/errors)
mod external {
    pub mod service {
        use tracing::{debug, error, info, trace, warn};

        pub async fn generate_events() {
            info!("External service info (should be dropped)");
            debug!("External service debug (should be dropped)");
            trace!("External service trace (should be dropped)");
            warn!("External service warning (should be captured)");
            error!("External service error (should be captured)");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }

    pub mod utils {
        use tracing::{debug, info, trace, warn};

        pub async fn generate_events() {
            info!("External utils info (should be dropped)");
            debug!("External utils debug (should be dropped)");
            trace!("External utils trace (should be dropped)");
            warn!("External utils warning (should be captured)");

            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    }
}