Function init_tracing

Source
pub fn init_tracing()
Expand description

§Logger Module

This module provides functionality for initializing and configuring the global tracing subscriber.

The logger is designed to be initialized once per application and provides comprehensive logging capabilities including structured logging, error context capture, and panic logging. Initializes a global [tracing] subscriber exactly once.

This function sets up a comprehensive tracing subscriber with the following features:

  • Environment-driven filtering - Uses RUST_LOG environment variable (defaults to info)
  • Flexible output format - JSON or compact format based on LOG_FORMAT environment variable
  • Error context capture - Adds [ErrorLayer] to capture span traces for better debugging
  • Panic logging - Replaces the default panic hook to log panics as structured events
  • Idempotent initialization - Safe to call multiple times from any thread

§Environment Variables

  • RUST_LOG: Controls log level filtering (e.g., info, debug, error)
  • LOG_FORMAT: Controls output format (json for JSON format, anything else for compact)

§Thread Safety

This function is thread-safe and can be called from any thread. Subsequent calls after the first successful initialization will be no-ops.

§Panics

This function will not panic, but if the tracing subscriber fails to initialize, subsequent calls to tracing macros will be no-ops.

§Examples

Basic usage:

use ds_common_logger_rs_lib::init_tracing;

init_tracing();
tracing::info!("Application started");

With environment variables:

RUST_LOG=debug LOG_FORMAT=json cargo run

In tests:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_logging() {
        init_tracing(); // Safe to call in tests
        tracing::info!("Test log message");
    }
}