scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! # Tracing Framework for SciRS2 v0.2.0
//!
//! This module provides structured logging and tracing capabilities using the `tracing` crate.
//! It enables zero-overhead instrumentation when disabled and comprehensive observability when enabled.
//!
//! # Features
//!
//! - **Structured Logging**: Rich, structured event logging with context
//! - **Span Management**: Hierarchical span tracking for nested operations
//! - **Multiple Outputs**: Console, file, JSON, and custom exporters
//! - **Performance Zones**: Named zones for performance tracking
//! - **Zero Overhead**: Compile-time elimination when feature is disabled
//!
//! # Example
//!
//! ```rust,no_run
//! use scirs2_core::profiling::tracing_framework::{TracingConfig, init_tracing};
//! use tracing::{info, span, Level};
//!
//! // Initialize tracing with default configuration
//! let _guard = init_tracing(TracingConfig::default()).expect("Failed to initialize tracing");
//!
//! // Create a span for a computation
//! let span = span!(Level::INFO, "matrix_multiply", size = 1000);
//! let _enter = span.enter();
//!
//! info!("Starting matrix multiplication");
//! // ... perform computation ...
//! info!(result = "success", "Matrix multiplication completed");
//! ```

#[cfg(feature = "profiling_advanced")]
use crate::CoreResult;
#[cfg(feature = "profiling_advanced")]
use std::path::PathBuf;
#[cfg(feature = "profiling_advanced")]
use tracing::Level;
#[cfg(feature = "profiling_advanced")]
use tracing_appender::non_blocking::WorkerGuard;
#[cfg(feature = "profiling_advanced")]
use tracing_subscriber::{
    fmt, layer::SubscriberExt, registry::LookupSpan, util::SubscriberInitExt, EnvFilter, Layer,
};

/// Configuration for tracing framework
#[cfg(feature = "profiling_advanced")]
#[derive(Debug, Clone)]
pub struct TracingConfig {
    /// Output format: "compact", "pretty", "json"
    pub format: TracingFormat,
    /// Log level filter
    pub level: Level,
    /// Enable ANSI color codes
    pub ansi_colors: bool,
    /// Log to file
    pub log_to_file: bool,
    /// Log file path
    pub log_file_path: Option<PathBuf>,
    /// Log file rotation: "hourly", "daily", "never"
    pub log_rotation: LogRotation,
    /// Enable flame graph generation
    pub enable_flame: bool,
    /// Enable Chrome DevTools format
    pub enable_chrome: bool,
    /// Custom environment filter
    pub env_filter: Option<String>,
}

/// Output format for tracing
#[cfg(feature = "profiling_advanced")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TracingFormat {
    /// Compact single-line format
    Compact,
    /// Pretty multi-line format with colors
    Pretty,
    /// JSON format for structured logging
    Json,
}

/// Log rotation strategy
#[cfg(feature = "profiling_advanced")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogRotation {
    /// Rotate logs hourly
    Hourly,
    /// Rotate logs daily
    Daily,
    /// No rotation
    Never,
}

#[cfg(feature = "profiling_advanced")]
impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            format: TracingFormat::Pretty,
            level: Level::INFO,
            ansi_colors: true,
            log_to_file: false,
            log_file_path: None,
            log_rotation: LogRotation::Daily,
            enable_flame: false,
            enable_chrome: false,
            env_filter: None,
        }
    }
}

#[cfg(feature = "profiling_advanced")]
impl TracingConfig {
    /// Create a production configuration (minimal overhead, JSON format)
    pub fn production() -> Self {
        Self {
            format: TracingFormat::Json,
            level: Level::WARN,
            ansi_colors: false,
            log_to_file: true,
            log_file_path: Some(PathBuf::from("/var/log/scirs2")),
            log_rotation: LogRotation::Daily,
            enable_flame: false,
            enable_chrome: false,
            env_filter: Some("scirs2=warn,scirs2_core=warn".to_string()),
        }
    }

    /// Create a development configuration (verbose, pretty format)
    pub fn development() -> Self {
        Self {
            format: TracingFormat::Pretty,
            level: Level::DEBUG,
            ansi_colors: true,
            log_to_file: false,
            log_file_path: None,
            log_rotation: LogRotation::Never,
            enable_flame: true,
            enable_chrome: false,
            env_filter: Some("scirs2=debug".to_string()),
        }
    }

    /// Create a configuration for benchmarking (flamegraph enabled)
    pub fn benchmark() -> Self {
        Self {
            format: TracingFormat::Compact,
            level: Level::INFO,
            ansi_colors: false,
            log_to_file: false,
            log_file_path: None,
            log_rotation: LogRotation::Never,
            enable_flame: true,
            enable_chrome: true,
            env_filter: Some("scirs2=info".to_string()),
        }
    }

    /// Set output format
    pub fn with_format(mut self, format: TracingFormat) -> Self {
        self.format = format;
        self
    }

    /// Set log level
    pub fn with_level(mut self, level: Level) -> Self {
        self.level = level;
        self
    }

    /// Enable file logging
    pub fn with_file_logging(mut self, path: PathBuf, rotation: LogRotation) -> Self {
        self.log_to_file = true;
        self.log_file_path = Some(path);
        self.log_rotation = rotation;
        self
    }

    /// Enable flame graph generation
    pub fn with_flame_graph(mut self, enable: bool) -> Self {
        self.enable_flame = enable;
        self
    }

    /// Set environment filter
    pub fn with_env_filter(mut self, filter: String) -> Self {
        self.env_filter = Some(filter);
        self
    }
}

/// Initialize the tracing framework
///
/// Returns a `WorkerGuard` that must be kept alive for the duration of the program.
/// When dropped, it will flush any remaining logs.
#[cfg(feature = "profiling_advanced")]
pub fn init_tracing(config: TracingConfig) -> CoreResult<Option<WorkerGuard>> {
    let env_filter = if let Some(ref filter) = config.env_filter {
        EnvFilter::try_new(filter).map_err(|e| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
                "Invalid env filter: {}",
                e
            )))
        })?
    } else {
        EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| EnvFilter::new(config.level.to_string()))
    };

    let registry = tracing_subscriber::registry().with(env_filter);

    // Configure file appender if enabled
    let guard = if config.log_to_file {
        let log_path = config.log_file_path.clone().ok_or_else(|| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(
                "Log file path not specified".to_string(),
            ))
        })?;

        let file_appender = match config.log_rotation {
            LogRotation::Hourly => tracing_appender::rolling::hourly(&log_path, "scirs2.log"),
            LogRotation::Daily => tracing_appender::rolling::daily(&log_path, "scirs2.log"),
            LogRotation::Never => tracing_appender::rolling::never(&log_path, "scirs2.log"),
        };

        let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);

        let file_layer = fmt::layer()
            .with_writer(non_blocking)
            .with_ansi(false)
            .json();

        registry.with(file_layer).init();

        Some(guard)
    } else {
        // Console output
        match config.format {
            TracingFormat::Compact => {
                registry
                    .with(fmt::layer().compact().with_ansi(config.ansi_colors))
                    .init();
            }
            TracingFormat::Pretty => {
                registry
                    .with(fmt::layer().pretty().with_ansi(config.ansi_colors))
                    .init();
            }
            TracingFormat::Json => {
                registry.with(fmt::layer().json().with_ansi(false)).init();
            }
        }

        None
    };

    Ok(guard)
}

/// Macro for creating a traced function
///
/// This macro automatically creates a span for the function and enters it.
#[macro_export]
#[cfg(feature = "profiling_advanced")]
macro_rules! traced_function {
    ($name:expr) => {
        let _span = tracing::info_span!($name).entered();
    };
    ($name:expr, $($field:tt)*) => {
        let _span = tracing::info_span!($name, $($field)*).entered();
    };
}

/// Macro for creating a performance zone
///
/// This creates a span that can be used for performance analysis.
#[macro_export]
#[cfg(feature = "profiling_advanced")]
macro_rules! perf_zone {
    ($name:expr) => {
        let _zone = tracing::trace_span!("perf", zone = $name).entered();
    };
    ($name:expr, $($field:tt)*) => {
        let _zone = tracing::trace_span!("perf", zone = $name, $($field)*).entered();
    };
}

/// Span guard for automatic span management
#[cfg(feature = "profiling_advanced")]
pub struct SpanGuard {
    _span: tracing::span::EnteredSpan,
}

#[cfg(feature = "profiling_advanced")]
impl SpanGuard {
    /// Create a new span guard
    pub fn new(name: &str) -> Self {
        Self {
            _span: tracing::info_span!(target: "scirs2::profiling", "{}", name).entered(),
        }
    }

    /// Create a span guard with fields
    pub fn with_fields(name: &str, fields: &[(&str, &dyn std::fmt::Display)]) -> Self {
        let span = tracing::info_span!(target: "scirs2::profiling", "{}", name);
        for (key, value) in fields {
            span.record(*key, &tracing::field::display(value));
        }
        Self {
            _span: span.entered(),
        }
    }
}

/// Performance zone marker for critical sections
#[cfg(feature = "profiling_advanced")]
pub struct PerfZone {
    _span: tracing::span::EnteredSpan,
    name: String,
    start: std::time::Instant,
}

#[cfg(feature = "profiling_advanced")]
impl PerfZone {
    /// Start a new performance zone
    pub fn start(name: &str) -> Self {
        let span = tracing::trace_span!(
            target: "scirs2::perf",
            "perf_zone",
            zone = name
        )
        .entered();

        Self {
            _span: span,
            name: name.to_string(),
            start: std::time::Instant::now(),
        }
    }

    /// End the performance zone and log duration
    pub fn end(self) {
        let duration = self.start.elapsed();
        tracing::info!(
            target: "scirs2::perf",
            zone = %self.name,
            duration_us = duration.as_micros(),
            "Performance zone completed"
        );
    }
}

#[cfg(feature = "profiling_advanced")]
impl Drop for PerfZone {
    fn drop(&mut self) {
        let duration = self.start.elapsed();
        tracing::debug!(
            target: "scirs2::perf",
            zone = %self.name,
            duration_us = duration.as_micros(),
            "Performance zone ended"
        );
    }
}

/// Stub implementations when profiling_advanced feature is disabled
#[cfg(not(feature = "profiling_advanced"))]
use crate::CoreResult;

#[cfg(not(feature = "profiling_advanced"))]
pub struct TracingConfig;

#[cfg(not(feature = "profiling_advanced"))]
impl Default for TracingConfig {
    fn default() -> Self {
        Self
    }
}

#[cfg(not(feature = "profiling_advanced"))]
impl TracingConfig {
    pub fn production() -> Self {
        Self
    }
    pub fn development() -> Self {
        Self
    }
    pub fn benchmark() -> Self {
        Self
    }
}

#[cfg(not(feature = "profiling_advanced"))]
pub fn init_tracing(_config: TracingConfig) -> CoreResult<Option<()>> {
    Ok(None)
}

#[cfg(test)]
#[cfg(feature = "profiling_advanced")]
mod tests {
    use super::*;

    #[test]
    fn test_tracing_config_defaults() {
        let config = TracingConfig::default();
        assert_eq!(config.format, TracingFormat::Pretty);
        assert_eq!(config.level, Level::INFO);
        assert!(config.ansi_colors);
        assert!(!config.log_to_file);
    }

    #[test]
    fn test_production_config() {
        let config = TracingConfig::production();
        assert_eq!(config.format, TracingFormat::Json);
        assert_eq!(config.level, Level::WARN);
        assert!(!config.ansi_colors);
        assert!(config.log_to_file);
    }

    #[test]
    fn test_development_config() {
        let config = TracingConfig::development();
        assert_eq!(config.format, TracingFormat::Pretty);
        assert_eq!(config.level, Level::DEBUG);
        assert!(config.ansi_colors);
        assert!(!config.log_to_file);
        assert!(config.enable_flame);
    }

    #[test]
    fn test_span_guard_creation() {
        let _guard = SpanGuard::new("test_span");
        // Should not panic
    }

    #[test]
    fn test_perf_zone() {
        let zone = PerfZone::start("test_zone");
        std::thread::sleep(std::time::Duration::from_millis(10));
        zone.end();
        // Should not panic
    }
}