irox_log/
lib.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5//!
6//! Basic console and file logging.
7//!
8
9#![forbid(unsafe_code)]
10#![warn(clippy::alloc_instead_of_core)]
11#![warn(clippy::std_instead_of_alloc)]
12#![warn(clippy::std_instead_of_core)]
13#![cfg_attr(not(feature = "std"), no_std)]
14#![cfg_attr(docsrs, feature(doc_cfg))]
15
16extern crate alloc;
17use irox_tools::cfg_feature_std;
18pub use log;
19
20cfg_feature_std! {
21    use core::str::FromStr;
22    use log::Level;
23    pub mod console;
24
25    macro_rules! set_con_logger {
26        ($name:ident) => {
27            if let Err(e) = log::set_logger(&console::$name) {
28                eprintln!("Error setting logger: {e:?}");
29            };
30        };
31    }
32
33    ///
34    /// Initializes the console logger to [`Level::Warn`]
35    pub fn init_console() {
36        init_console_level(Level::Warn);
37    }
38
39    ///
40    /// Initializes the console logger to the specified [`Level`]
41    pub fn init_console_level(max_level: Level) {
42        log::set_max_level(max_level.to_level_filter());
43        match max_level {
44            Level::Error => {
45                set_con_logger!(ERROR_LOGGER);
46            }
47            Level::Warn => {
48                set_con_logger!(WARN_LOGGER);
49            }
50            Level::Info => {
51                set_con_logger!(INFO_LOGGER);
52            }
53            Level::Debug => {
54                set_con_logger!(DEBUG_LOGGER);
55            }
56            Level::Trace => {
57                set_con_logger!(TRACE_LOGGER);
58            }
59        }
60    }
61
62    ///
63    /// Initializes the console logger from the configuration in the specified
64    /// environment variable.
65    pub fn init_console_from_env(varbl: &str) {
66        if let Ok(level) = std::env::var(varbl) {
67            let Ok(level) = Level::from_str(&level) else {
68                return;
69            };
70            init_console_level(level);
71        } else {
72            init_console_level(Level::Warn);
73        }
74    }
75}