stackdriver_logger/
macros.rs

1use crate::{try_init, Service};
2use toml::Value;
3
4/// Initialize the logger using your project's TOML file.
5///
6/// This initializer includes your Cargo.toml file at compile time and extract the
7/// service name and version at run time.
8/// ## Usage
9/// This is the basic form :
10/// ```rust
11/// use log::info;
12///
13/// stackdriver_logger::init_with_cargo!();
14/// info!("Default path used for Cargo.toml : ../Cargo.toml");
15/// ```
16/// You can also specify the path if you need to :
17/// ```rust
18/// use log::info;
19///
20/// stackdriver_logger::init_with_cargo!("../Cargo.toml");
21/// info!("Path was specified !");
22/// ```
23/// Note that the `init_with_cargo!` macro will include your `Cargo.toml` in the resulting binary.
24/// If you don't want that, take a look at the other initializers.
25#[macro_export]
26macro_rules! init_with_cargo {
27    ($e:expr) => {{
28        let base = include_str!($e);
29        $crate::macros::read_cargo(base);
30    }};
31    () => {{
32        let base = include_str!("../Cargo.toml");
33        $crate::macros::read_cargo(base);
34    }};
35}
36
37#[doc(hidden)]
38pub fn read_cargo(input: &str) {
39    input
40        .parse::<Value>()
41        .ok()
42        .and_then(|toml: Value| -> Option<()> {
43            let service = Service {
44                name: read_package_key(&toml, "name")?,
45                version: read_package_key(&toml, "version")?,
46            };
47
48            try_init(Some(service), true).expect("Could not initialize stackdriver_logger");
49            None
50        });
51}
52
53fn read_package_key(toml: &Value, key: &str) -> Option<String> {
54    let key = toml
55        .get("package")?
56        .as_table()?
57        .get(key)?
58        .as_str()?
59        .to_owned();
60
61    Some(key)
62}