acap_logging/
lib.rs

1#![allow(clippy::needless_doctest_main)]
2#![doc = include_str!("../README.md")]
3use std::{env, io::IsTerminal};
4
5use log::debug;
6
7fn init_syslog() {
8    let formatter = syslog::Formatter3164::default();
9    let logger = syslog::unix(formatter).unwrap();
10    log::set_boxed_logger(Box::new(syslog::BasicLogger::new(logger))).unwrap();
11    log::set_max_level(log::LevelFilter::Debug);
12}
13
14/// Set up app-logging as appropriate for the environment, then run the provided function.
15///
16/// If stdout is a terminal, write to stderr.
17/// Otherwise, write to the system logger.
18///
19/// # Panics
20///
21/// This function will panic if
22/// it fails to initialize the appropriate logger or
23/// a global logger has already been initialized.
24pub fn init_logger() {
25    // Using `su -pc "..."` just says the "Connection to ... closed", and
26    // I have not found another way to run as the SDK user over ssh and allocate a tty, so
27    // if we detect an `env_logger` configuration we write to stderr anyway.
28    if std::io::stdout().is_terminal()
29        || env::var_os("RUST_LOG").is_some()
30        || env::var_os("RUST_LOG_STYLE").is_some()
31    {
32        env_logger::init();
33    } else {
34        init_syslog();
35    }
36    debug!("Logging initialized");
37}