1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Bumble & Python logging
16 
17 use pyo3::types::PyDict;
18 use pyo3::{intern, types::PyModule, PyResult, Python};
19 use std::env;
20 
21 /// Returns the uppercased contents of the `BUMBLE_LOGLEVEL` env var, or `default` if it is not present or not UTF-8.
22 ///
23 /// The result could be passed to [py_logging_basic_config] to configure Python's logging
24 /// accordingly.
bumble_env_logging_level(default: impl Into<String>) -> String25 pub fn bumble_env_logging_level(default: impl Into<String>) -> String {
26     env::var("BUMBLE_LOGLEVEL")
27         .unwrap_or_else(|_| default.into())
28         .to_ascii_uppercase()
29 }
30 
31 /// Call `logging.basicConfig` with the provided logging level
py_logging_basic_config(log_level: impl Into<String>) -> PyResult<()>32 pub fn py_logging_basic_config(log_level: impl Into<String>) -> PyResult<()> {
33     Python::with_gil(|py| {
34         let kwargs = PyDict::new(py);
35         kwargs.set_item("level", log_level.into())?;
36 
37         PyModule::import(py, intern!(py, "logging"))?
38             .call_method(intern!(py, "basicConfig"), (), Some(kwargs))
39             .map(|_| ())
40     })
41 }
42