foxy/logging/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Logging utilities for Foxy.
6//!
7//! This module provides centralized logging configuration and helper functions
8//! for consistent logging throughout the application.
9
10use log::{debug, error, info, trace, warn, LevelFilter};
11use std::sync::Once;
12
13static INIT: Once = Once::new();
14
15/// Initialize logging with the specified level.
16///
17/// This function ensures logging is only initialized once.
18pub fn init(level: Option<LevelFilter>) {
19    INIT.call_once(|| {
20        let env = env_logger::Env::default()
21            .filter_or("RUST_LOG", level.map_or("info", |l| match l {
22                LevelFilter::Trace => "trace",
23                LevelFilter::Debug => "debug",
24                LevelFilter::Info => "info",
25                LevelFilter::Warn => "warn",
26                LevelFilter::Error => "error",
27                LevelFilter::Off => "off",
28            }));
29
30        env_logger::Builder::from_env(env)
31            .format_timestamp_millis()
32            .format_target(true)
33            .init();
34
35        info!("Logging initialized at level: {}", log::max_level());
36    });
37}
38
39/// Log an error with context and return the error.
40///
41/// This is useful for logging errors in a chain of Results.
42pub fn log_error<E: std::fmt::Display>(context: &str, err: E) -> E {
43    error!("{}: {}", context, err);
44    err
45}
46
47/// Log a warning with context.
48pub fn log_warning<E: std::fmt::Display>(context: &str, err: E) {
49    warn!("{}: {}", context, err);
50}
51
52/// Log a debug message with context.
53pub fn log_debug<M: std::fmt::Display>(context: &str, msg: M) {
54    debug!("{}: {}", context, msg);
55}
56
57/// Log a trace message with context.
58pub fn log_trace<M: std::fmt::Display>(context: &str, msg: M) {
59    trace!("{}: {}", context, msg);
60}
61
62/// Log an info message with context.
63pub fn log_info<M: std::fmt::Display>(context: &str, msg: M) {
64    info!("{}: {}", context, msg);
65}