Skip to main content

ggen_core/
simple_tracing.rs

1//! Simple tracing system for pipeline debugging
2//!
3//! This module provides a lightweight tracing system for debugging template processing
4//! and generation operations. It uses environment variables for configuration and
5//! provides structured logging for key pipeline operations.
6//!
7//! ## Features
8//!
9//! - **Environment-based configuration**: Controlled via `GGEN_TRACE` environment variable
10//! - **Multiple trace levels**: Error, Warn, Info, Debug, Trace
11//! - **Performance timing**: Built-in timer for measuring operation duration
12//! - **Structured logging**: Context-aware logging for templates, RDF, SPARQL, etc.
13//!
14//! ## Configuration
15//!
16//! Set the `GGEN_TRACE` environment variable to enable tracing:
17//!
18//! - `error` - Only error messages
19//! - `warn` - Warnings and errors
20//! - `info` - Informational messages (default)
21//! - `debug` - Debug information
22//! - `trace` - Verbose trace information
23//! - `1`, `true`, `yes` - Enable debug level
24//! - `0`, `false`, `no` - Disable (error only)
25//!
26//! ## Examples
27//!
28//! ### Basic Usage
29//!
30//! ```rust,no_run
31//! use crate::simple_tracing::SimpleTracer;
32//! use std::path::Path;
33//!
34//! // Check if tracing is enabled
35//! if SimpleTracer::is_enabled() {
36//!     SimpleTracer::template_start(Path::new("template.tmpl"));
37//! }
38//! ```
39//!
40//! ### Performance Timing
41//!
42//! ```rust,no_run
43//! use crate::simple_tracing::SimpleTimer;
44//!
45//! let timer = SimpleTimer::start("template_processing");
46//! // ... do work ...
47//! timer.finish(); // Automatically logs the duration
48//! ```
49//!
50//! ### Using the Macro
51//!
52//! ```rust,no_run
53//! use crate::time_operation;
54//!
55//! let result = time_operation!("expensive_operation", {
56//!     // ... operation code ...
57//!     42
58//! });
59//! ```
60
61/// Macro to time an operation and record it in the current trace.
62#[macro_export]
63macro_rules! simple_time_operation {
64    ($name:expr, $block:block) => {{
65        let start = std::time::Instant::now();
66        let result = $block;
67        let elapsed = start.elapsed();
68        $crate::simple_tracing::SimpleTracer::performance($name, elapsed.as_millis() as u64);
69        result
70    }};
71}
72
73use std::path::Path;
74use std::time::Instant;
75
76/// Simple tracing system for pipeline debugging
77pub struct SimpleTracer;
78
79impl SimpleTracer {
80    /// Check if tracing is enabled
81    pub fn is_enabled() -> bool {
82        std::env::var("GGEN_TRACE").is_ok()
83    }
84
85    /// Get trace level
86    pub fn trace_level() -> TraceLevel {
87        match std::env::var("GGEN_TRACE")
88            .unwrap_or_default()
89            .to_lowercase()
90            .as_str()
91        {
92            "error" => TraceLevel::Error,
93            "warn" => TraceLevel::Warn,
94            "info" => TraceLevel::Info,
95            "debug" => TraceLevel::Debug,
96            "trace" => TraceLevel::Trace,
97            "1" | "true" | "yes" => TraceLevel::Debug,
98            "0" | "false" | "no" => TraceLevel::Error,
99            _ => TraceLevel::Info,
100        }
101    }
102
103    /// Log a trace message
104    pub fn trace(level: TraceLevel, message: &str, context: Option<&str>) {
105        if !Self::is_enabled() {
106            return;
107        }
108
109        let current_level = Self::trace_level();
110        if level as u8 > current_level as u8 {
111            return;
112        }
113
114        let prefix = match level {
115            TraceLevel::Error => "ERROR",
116            TraceLevel::Warn => "WARN ",
117            TraceLevel::Info => "INFO ",
118            TraceLevel::Debug => "DEBUG",
119            TraceLevel::Trace => "TRACE",
120        };
121
122        match level {
123            TraceLevel::Error => {
124                if let Some(ctx) = context {
125                    log::error!("[GGEN {}] {}: {}", prefix, ctx, message);
126                } else {
127                    log::error!("[GGEN {}] {}", prefix, message);
128                }
129            }
130            TraceLevel::Warn => {
131                if let Some(ctx) = context {
132                    log::warn!("[GGEN {}] {}: {}", prefix, ctx, message);
133                } else {
134                    log::warn!("[GGEN {}] {}", prefix, message);
135                }
136            }
137            TraceLevel::Info => {
138                if let Some(ctx) = context {
139                    log::info!("[GGEN {}] {}: {}", prefix, ctx, message);
140                } else {
141                    log::info!("[GGEN {}] {}", prefix, message);
142                }
143            }
144            TraceLevel::Debug | TraceLevel::Trace => {
145                if let Some(ctx) = context {
146                    log::debug!("[GGEN {}] {}: {}", prefix, ctx, message);
147                } else {
148                    log::debug!("[GGEN {}] {}", prefix, message);
149                }
150            }
151        }
152    }
153
154    /// Log template processing start
155    pub fn template_start(template_path: &Path) {
156        Self::trace(
157            TraceLevel::Info,
158            &format!("Starting template processing: {}", template_path.display()),
159            None,
160        );
161    }
162
163    /// Log template processing completion
164    pub fn template_complete(template_path: &Path, output_path: &Path, content_size: usize) {
165        Self::trace(
166            TraceLevel::Info,
167            &format!(
168                "Template processing complete: {} -> {} ({} bytes)",
169                template_path.display(),
170                output_path.display(),
171                content_size
172            ),
173            None,
174        );
175    }
176
177    /// Log frontmatter processing
178    pub fn frontmatter_processed(frontmatter: &crate::template_types::Frontmatter) {
179        Self::trace(
180            TraceLevel::Debug,
181            &format!(
182                "Frontmatter processed: to={:?}, inject={}",
183                frontmatter.to,
184                frontmatter.flags.inject // ❌ REMOVED: vars count - no longer in frontmatter
185            ),
186            Some("frontmatter"),
187        );
188    }
189
190    /// Log context blessing
191    pub fn context_blessed(vars_count: usize) {
192        Self::trace(
193            TraceLevel::Debug,
194            &format!(
195                "Context blessed: {} variables (Name, locals added)",
196                vars_count
197            ),
198            Some("context"),
199        );
200    }
201
202    /// Log RDF loading
203    pub fn rdf_loading(files: &[String], inline_blocks: usize, triples: usize) {
204        Self::trace(
205            TraceLevel::Info,
206            &format!(
207                "RDF loaded: {} files, {} inline blocks, {} triples",
208                files.len(),
209                inline_blocks,
210                triples
211            ),
212            Some("rdf"),
213        );
214    }
215
216    /// Log SPARQL query
217    pub fn sparql_query(query: &str, result_count: Option<usize>) {
218        let count_str = result_count
219            .map(|c| c.to_string())
220            .unwrap_or_else(|| "N/A".to_string());
221        Self::trace(
222            TraceLevel::Debug,
223            &format!("SPARQL query: {} results", count_str),
224            Some("sparql"),
225        );
226        Self::trace(TraceLevel::Trace, query, Some("sparql"));
227    }
228
229    /// Log file injection
230    pub fn file_injection(target_path: &Path, mode: &str, success: bool) {
231        let status = if success { "completed" } else { "failed" };
232        Self::trace(
233            TraceLevel::Info,
234            &format!("File injection {}: {} mode", status, mode),
235            Some(&format!("injection:{}", target_path.display())),
236        );
237    }
238
239    /// Log shell hook
240    pub fn shell_hook(command: &str, timing: &str, exit_code: i32) {
241        let status = if exit_code == 0 {
242            "completed"
243        } else {
244            "failed"
245        };
246        Self::trace(
247            TraceLevel::Info,
248            &format!(
249                "Shell hook {}: {} (exit code: {})",
250                status, timing, exit_code
251            ),
252            Some(&format!("hook:{}", command)),
253        );
254    }
255
256    /// Log performance metric
257    pub fn performance(operation: &str, duration_ms: u64) {
258        Self::trace(
259            TraceLevel::Debug,
260            &format!("Performance: {} took {}ms", operation, duration_ms),
261            Some("performance"),
262        );
263    }
264
265    /// Log dry run
266    pub fn dry_run(output_path: &Path, content_size: usize) {
267        Self::trace(
268            TraceLevel::Info,
269            &format!(
270                "DRY RUN: Would generate {} ({} bytes)",
271                output_path.display(),
272                content_size
273            ),
274            Some("dry_run"),
275        );
276    }
277
278    /// Log backup creation
279    pub fn backup_created(original_path: &Path, backup_path: &Path) {
280        Self::trace(
281            TraceLevel::Info,
282            &format!(
283                "Backup created: {} -> {}",
284                original_path.display(),
285                backup_path.display()
286            ),
287            Some("backup"),
288        );
289    }
290
291    /// Log skip condition
292    pub fn skip_condition(condition: &str, reason: &str) {
293        Self::trace(
294            TraceLevel::Info,
295            &format!("Skipped: {} ({})", condition, reason),
296            Some("skip"),
297        );
298    }
299
300    /// Log error
301    pub fn error(error: &crate::utils::error::Error, context: &str) {
302        Self::trace(
303            TraceLevel::Error,
304            &format!("Error in {}: {}", context, error),
305            Some("error"),
306        );
307    }
308
309    /// Log warning
310    pub fn warning(message: &str, context: Option<&str>) {
311        Self::trace(TraceLevel::Warn, message, context);
312    }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
316pub enum TraceLevel {
317    Error = 0,
318    Warn = 1,
319    Info = 2,
320    Debug = 3,
321    Trace = 4,
322}
323
324/// Performance timer for measuring operation duration
325pub struct SimpleTimer {
326    start: Instant,
327    operation: String,
328}
329
330impl SimpleTimer {
331    /// Start timing an operation
332    pub fn start(operation: &str) -> Self {
333        Self {
334            start: Instant::now(),
335            operation: operation.to_string(),
336        }
337    }
338
339    /// Finish timing and log the result
340    pub fn finish(self) {
341        let duration = self.start.elapsed();
342        SimpleTracer::performance(&self.operation, duration.as_millis() as u64);
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349    use crate::time_operation;
350    use std::fs;
351    use tempfile::TempDir;
352
353    #[test]
354    fn test_trace_level_ordering() {
355        assert!(TraceLevel::Error < TraceLevel::Warn);
356        assert!(TraceLevel::Warn < TraceLevel::Info);
357        assert!(TraceLevel::Info < TraceLevel::Debug);
358        assert!(TraceLevel::Debug < TraceLevel::Trace);
359    }
360
361    #[test]
362    fn test_simple_timer() {
363        let timer = SimpleTimer::start("test_operation");
364        std::thread::sleep(std::time::Duration::from_millis(10));
365        timer.finish(); // Should not panic
366    }
367
368    #[test]
369    fn test_tracing_methods() {
370        let temp_dir = TempDir::new().unwrap();
371        let test_path = temp_dir.path().join("test.tmpl");
372        fs::write(&test_path, "test content").unwrap();
373
374        // Test all tracing methods compile and work
375        SimpleTracer::template_start(&test_path);
376        SimpleTracer::template_complete(&test_path, &test_path, 100);
377
378        let frontmatter = crate::template_types::Frontmatter::default();
379        SimpleTracer::frontmatter_processed(&frontmatter);
380
381        SimpleTracer::context_blessed(5);
382        SimpleTracer::rdf_loading(&["file1.ttl".to_string()], 2, 100);
383        SimpleTracer::sparql_query("SELECT * WHERE { ?s ?p ?o }", Some(10));
384
385        SimpleTracer::file_injection(&test_path, "append", true);
386        SimpleTracer::shell_hook("echo 'test'", "before", 0);
387        SimpleTracer::performance("test_operation", 50);
388        SimpleTracer::dry_run(&test_path, 500);
389        SimpleTracer::backup_created(&test_path, &temp_dir.path().join("backup.tmpl"));
390        SimpleTracer::skip_condition("skip_if", "pattern found");
391
392        let error = crate::utils::error::Error::new("Test error");
393        SimpleTracer::error(&error, "test context");
394        SimpleTracer::warning("Test warning", Some("test context"));
395        SimpleTracer::warning("Test warning", None);
396    }
397
398    #[test]
399    fn test_tracing_environment_variables() {
400        // Test different GGEN_TRACE values
401        let test_values = [
402            "error", "warn", "info", "debug", "trace", "1", "0", "true", "false",
403        ];
404
405        for value in &test_values {
406            std::env::set_var("GGEN_TRACE", value);
407            let level = SimpleTracer::trace_level();
408            assert!(matches!(
409                level,
410                TraceLevel::Error
411                    | TraceLevel::Warn
412                    | TraceLevel::Info
413                    | TraceLevel::Debug
414                    | TraceLevel::Trace
415            ));
416        }
417    }
418
419    #[test]
420    fn test_time_operation_macro() {
421        let result = time_operation!("test_op", {
422            std::thread::sleep(std::time::Duration::from_millis(2));
423            42
424        });
425        assert_eq!(result, 42);
426    }
427}