prax_query/logging.rs
1//! Logging infrastructure for Prax ORM.
2//!
3//! This module provides structured JSON logging controlled by the `PRAX_DEBUG` environment variable.
4//!
5//! # Environment Variables
6//!
7//! - `PRAX_DEBUG=true` - Enable debug logging
8//! - `PRAX_DEBUG=1` - Enable debug logging
9//! - `PRAX_LOG_LEVEL=debug|info|warn|error|trace` - Set specific log level
10//! - `PRAX_LOG_FORMAT=json|pretty|compact` - Set output format (default: json)
11//!
12//! # Usage
13//!
14//! ```rust,no_run
15//! use prax_query::logging;
16//!
17//! // Initialize logging (call once at startup)
18//! logging::init();
19//!
20//! // Or with custom settings
21//! logging::init_with_level("debug");
22//! ```
23//!
24//! # Internal Logging
25//!
26//! Within Prax, use the standard tracing macros:
27//!
28//! ```rust,ignore
29//! use tracing::{debug, info, warn, error, trace};
30//!
31//! debug!(filter = ?filter, "Building SQL for filter");
32//! info!(table = %table, "Executing query");
33//! warn!(latency_ms = %ms, "Slow query detected");
34//! error!(error = %e, "Query failed");
35//! ```
36
37use std::env;
38use std::sync::Once;
39
40static INIT: Once = Once::new();
41
42/// Check if debug logging is enabled via `PRAX_DEBUG` environment variable.
43///
44/// Returns `true` if `PRAX_DEBUG` is set to "true", "1", or "yes" (case-insensitive).
45#[inline]
46pub fn is_debug_enabled() -> bool {
47 env::var("PRAX_DEBUG")
48 .map(|v| matches!(v.to_lowercase().as_str(), "true" | "1" | "yes"))
49 .unwrap_or(false)
50}
51
52/// Get the configured log level from `PRAX_LOG_LEVEL` environment variable.
53///
54/// Defaults to "debug" if `PRAX_DEBUG` is enabled, otherwise "warn".
55pub fn get_log_level() -> &'static str {
56 if let Ok(level) = env::var("PRAX_LOG_LEVEL") {
57 match level.to_lowercase().as_str() {
58 "trace" => "trace",
59 "debug" => "debug",
60 "info" => "info",
61 "warn" => "warn",
62 "error" => "error",
63 _ => if is_debug_enabled() { "debug" } else { "warn" },
64 }
65 } else if is_debug_enabled() {
66 "debug"
67 } else {
68 "warn"
69 }
70}
71
72/// Get the configured log format from `PRAX_LOG_FORMAT` environment variable.
73///
74/// Defaults to "json" for structured logging.
75pub fn get_log_format() -> &'static str {
76 env::var("PRAX_LOG_FORMAT")
77 .map(|f| match f.to_lowercase().as_str() {
78 "pretty" => "pretty",
79 "compact" => "compact",
80 _ => "json",
81 })
82 .unwrap_or("json")
83}
84
85/// Initialize the Prax logging system.
86///
87/// This should be called once at application startup. Subsequent calls are no-ops.
88///
89/// Logging is controlled by:
90/// - `PRAX_DEBUG=true` - Enable debug-level logging
91/// - `PRAX_LOG_LEVEL` - Override the log level (trace, debug, info, warn, error)
92/// - `PRAX_LOG_FORMAT` - Output format (pretty, json, compact)
93///
94/// # Example
95///
96/// ```rust,no_run
97/// use prax_query::logging;
98///
99/// // Initialize at the start of your application
100/// logging::init();
101/// ```
102pub fn init() {
103 INIT.call_once(|| {
104 if !is_debug_enabled() && env::var("PRAX_LOG_LEVEL").is_err() {
105 // No logging requested, skip initialization
106 return;
107 }
108
109 #[cfg(feature = "tracing-subscriber")]
110 {
111 use tracing_subscriber::{fmt, EnvFilter, prelude::*};
112
113 let level = get_log_level();
114 let filter = EnvFilter::try_new(format!("prax={},prax_query={},prax_schema={}", level, level, level))
115 .unwrap_or_else(|_| EnvFilter::new("warn"));
116
117 match get_log_format() {
118 "json" => {
119 tracing_subscriber::registry()
120 .with(filter)
121 .with(fmt::layer().json())
122 .init();
123 }
124 "compact" => {
125 tracing_subscriber::registry()
126 .with(filter)
127 .with(fmt::layer().compact())
128 .init();
129 }
130 _ => {
131 tracing_subscriber::registry()
132 .with(filter)
133 .with(fmt::layer().pretty())
134 .init();
135 }
136 }
137
138 tracing::info!(
139 level = level,
140 format = get_log_format(),
141 "Prax logging initialized"
142 );
143 }
144
145 #[cfg(not(feature = "tracing-subscriber"))]
146 {
147 // Tracing subscriber not available, logging will be silent
148 // unless the user sets up their own subscriber
149 }
150 });
151}
152
153/// Initialize logging with a specific level.
154///
155/// # Example
156///
157/// ```rust,no_run
158/// use prax_query::logging;
159///
160/// // Enable trace-level logging
161/// logging::init_with_level("trace");
162/// ```
163///
164/// # Safety
165///
166/// This function modifies environment variables, which is unsafe in
167/// multi-threaded programs. Call this early in your program before
168/// spawning threads.
169pub fn init_with_level(level: &str) {
170 // SAFETY: This should only be called at program startup before threads are spawned.
171 // The user is responsible for calling this safely.
172 unsafe {
173 env::set_var("PRAX_LOG_LEVEL", level);
174 }
175 init();
176}
177
178/// Initialize logging for debugging (convenience function).
179///
180/// Equivalent to setting `PRAX_DEBUG=true` and calling `init()`.
181///
182/// # Safety
183///
184/// This function modifies environment variables, which is unsafe in
185/// multi-threaded programs. Call this early in your program before
186/// spawning threads.
187pub fn init_debug() {
188 // SAFETY: This should only be called at program startup before threads are spawned.
189 unsafe {
190 env::set_var("PRAX_DEBUG", "true");
191 }
192 init();
193}
194
195/// Macro for conditional debug logging.
196///
197/// Only logs if `PRAX_DEBUG` is enabled at runtime.
198#[macro_export]
199macro_rules! prax_debug {
200 ($($arg:tt)*) => {
201 if $crate::logging::is_debug_enabled() {
202 tracing::debug!($($arg)*);
203 }
204 };
205}
206
207/// Macro for conditional trace logging.
208#[macro_export]
209macro_rules! prax_trace {
210 ($($arg:tt)*) => {
211 if $crate::logging::is_debug_enabled() {
212 tracing::trace!($($arg)*);
213 }
214 };
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn test_debug_disabled_by_default() {
223 // Clear env var to test default behavior
224 // SAFETY: Test runs in isolation
225 unsafe {
226 env::remove_var("PRAX_DEBUG");
227 }
228 assert!(!is_debug_enabled());
229 }
230
231 #[test]
232 fn test_log_level_default() {
233 // SAFETY: Test runs in isolation
234 unsafe {
235 env::remove_var("PRAX_DEBUG");
236 env::remove_var("PRAX_LOG_LEVEL");
237 }
238 assert_eq!(get_log_level(), "warn");
239 }
240}