Skip to main content

ggen_core/
tracing.rs

1use std::path::Path;
2use tracing::info;
3
4/// Initialize tracing based on environment variables
5pub fn init_tracing() -> crate::utils::error::Result<()> {
6    #[cfg(feature = "otel")]
7    {
8        init_otel_tracing()
9    }
10
11    #[cfg(not(feature = "otel"))]
12    {
13        use tracing_subscriber::EnvFilter;
14        let env_filter =
15            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("ggen=info"));
16
17        tracing_subscriber::fmt()
18            .with_env_filter(env_filter)
19            .try_init()
20            .map_err(|e| {
21                crate::utils::error::Error::with_source("Failed to initialize tracing", e)
22            })?;
23
24        Ok(())
25    }
26}
27
28#[cfg(feature = "otel")]
29fn init_otel_tracing() -> crate::utils::error::Result<()> {
30    // OTEL feature disabled - API breaking changes in opentelemetry crates
31    // Use standard tracing instead
32    use tracing_subscriber::EnvFilter;
33
34    let env_filter =
35        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("ggen=info"));
36
37    tracing_subscriber::fmt()
38        .with_env_filter(env_filter)
39        .try_init()
40        .map_err(|e| crate::utils::error::Error::with_source("Failed to initialize tracing", e))?;
41
42    Ok(())
43}
44
45/// Shutdown tracing and flush providers
46pub fn shutdown_tracing() {
47    // OTEL feature disabled - no provider to shutdown
48    #[cfg(feature = "otel")]
49    {
50        // opentelemetry::global::shutdown_tracer_provider();  // Not available in current version
51    }
52}
53
54/// Pipeline tracer for structured logging of template operations
55pub struct PipelineTracer;
56
57impl PipelineTracer {
58    /// Create a tracing span for template processing
59    pub fn template_span(template_path: &Path) -> tracing::Span {
60        tracing::info_span!(
61            "template_processing",
62            template = %template_path.display()
63        )
64    }
65
66    /// Log frontmatter processing
67    pub fn frontmatter_processed(front: &crate::template_types::Frontmatter) {
68        info!(
69            target = %front.to.as_deref().unwrap_or("unknown"),
70            "Frontmatter processed"
71        );
72    }
73
74    /// Log context blessing
75    pub fn context_blessed(vars_count: usize) {
76        info!(vars_count = vars_count, "Template context blessed");
77    }
78
79    /// Log template parsing completion
80    pub fn template_parsing_complete(template_path: &Path, content_size: usize) {
81        info!(
82            template = %template_path.display(),
83            content_size = content_size,
84            "Template parsing completed"
85        );
86    }
87
88    /// Log template rendering start
89    pub fn template_rendering_start(output_path: &Path) {
90        info!(
91            output_path = %output_path.display(),
92            "Starting template rendering"
93        );
94    }
95
96    /// Log template rendering completion
97    pub fn template_rendering_complete(output_path: &Path, content_size: usize) {
98        info!(
99            output_path = %output_path.display(),
100            content_size = content_size,
101            "Template rendering completed"
102        );
103    }
104
105    /// Log template start
106    pub fn template_start(template_path: &Path) {
107        info!(
108            template = %template_path.display(),
109            "Starting template processing"
110        );
111    }
112
113    /// Log RDF loading start
114    pub fn rdf_loading_start(files: &[String], inline_blocks: usize) {
115        info!(
116            files_count = files.len(),
117            inline_blocks = inline_blocks,
118            "Loading RDF data"
119        );
120    }
121
122    /// Log RDF loading completion
123    pub fn rdf_loading_complete(triples_count: usize) {
124        info!(triples_count = triples_count, "RDF loading completed");
125    }
126
127    /// Log SPARQL query execution
128    pub fn sparql_query(query: &str, results: Option<usize>) {
129        info!(
130            query_len = query.len(),
131            results_count = results.unwrap_or(0),
132            "SPARQL query executed"
133        );
134    }
135
136    /// Log file injection start
137    pub fn file_injection_start(path: &Path, mode: &str) {
138        info!(
139            path = %path.display(),
140            mode = mode,
141            "Starting file injection"
142        );
143    }
144
145    /// Log file injection completion
146    pub fn file_injection_complete(path: &Path, mode: &str) {
147        info!(
148            path = %path.display(),
149            mode = mode,
150            "File injection completed"
151        );
152    }
153
154    /// Log shell hook start
155    pub fn shell_hook_start(command: &str, timing: &str) {
156        info!(command = command, timing = timing, "Executing shell hook");
157    }
158
159    /// Log shell hook completion
160    pub fn shell_hook_complete(command: &str, timing: &str, exit_code: i32) {
161        info!(
162            command = command,
163            timing = timing,
164            exit_code = exit_code,
165            "Shell hook completed"
166        );
167    }
168
169    /// Log performance metric
170    pub fn performance_metric(operation: &str, duration_ms: u64) {
171        info!(
172            operation = operation,
173            duration_ms = duration_ms,
174            "Performance metric recorded"
175        );
176    }
177
178    /// Log error with context
179    pub fn error_with_context(error: &crate::utils::error::Error, context: &str) {
180        tracing::error!(
181            error = %error,
182            context = context,
183            "Error occurred"
184        );
185    }
186
187    /// Log warning
188    pub fn warning(message: &str, context: Option<&str>) {
189        tracing::warn!(
190            message = message,
191            context = context.unwrap_or(""),
192            "Warning"
193        );
194    }
195
196    /// Log backup creation
197    pub fn backup_created(original: &Path, backup: &Path) {
198        info!(
199            original = %original.display(),
200            backup = %backup.display(),
201            "Backup created"
202        );
203    }
204
205    /// Log skip condition
206    pub fn skip_condition(condition: &str, reason: &str) {
207        info!(condition = condition, reason = reason, "Template skipped");
208    }
209
210    /// Log dry run information
211    pub fn dry_run(path: &Path, size: usize) {
212        info!(
213            path = %path.display(),
214            size = size,
215            "Dry run: skipping file write"
216        );
217    }
218}
219
220/// Performance timer for measuring operation duration (RAII)
221pub struct PerformanceTimer {
222    operation: String,
223    start: std::time::Instant,
224    finished: bool,
225}
226
227impl PerformanceTimer {
228    /// Start a new performance timer
229    pub fn start(operation: &str) -> Self {
230        Self {
231            operation: operation.to_string(),
232            start: std::time::Instant::now(),
233            finished: false,
234        }
235    }
236
237    /// Finish the timer and record the duration
238    pub fn finish(mut self) {
239        if !self.finished {
240            let duration = self.start.elapsed();
241            PipelineTracer::performance_metric(&self.operation, duration.as_millis() as u64);
242            self.finished = true;
243        }
244    }
245}
246
247impl Drop for PerformanceTimer {
248    fn drop(&mut self) {
249        if !self.finished {
250            let duration = self.start.elapsed();
251            PipelineTracer::performance_metric(&self.operation, duration.as_millis() as u64);
252        }
253    }
254}
255
256/// Macro to time an operation using PerformanceTimer
257#[macro_export]
258macro_rules! time_operation {
259    ($name:expr, $block:block) => {{
260        let _timer = $crate::tracing::PerformanceTimer::start($name);
261        $block
262    }};
263}
264
265/// Macro to create a tracing span
266#[macro_export]
267macro_rules! trace_span {
268    ($name:expr, $($fields:tt)*) => {
269        tracing::info_span!($name, $($fields)*)
270    };
271}
272
273pub use time_operation;
274pub use trace_span;