cargo_auto/
generic_functions_mod.rs

1// generic_functions.rs
2
3//! Functions to work with CLI binary executable projects.
4//!
5//! Binary executables need some standard functions to help to develop them efficiently.
6
7// region: Public API constants
8// ANSI colors for Linux terminal
9// https://github.com/shiena/ansicolor/blob/master/README.md
10/// ANSI color
11#[allow(dead_code)]
12pub const RED: &str = "\x1b[31m";
13/// ANSI color
14#[allow(dead_code)]
15pub const GREEN: &str = "\x1b[32m";
16/// ANSI color
17#[allow(dead_code)]
18pub const YELLOW: &str = "\x1b[33m";
19/// ANSI color
20#[allow(dead_code)]
21pub const BLUE: &str = "\x1b[34m";
22/// ANSI color
23#[allow(dead_code)]
24pub const RESET: &str = "\x1b[0m";
25// endregion: Public API constants
26
27/// Initialize tracing to file logs/cargo_auto.log.  \
28///
29/// The folder logs/ is in .gitignore and will not be committed.  
30pub fn tracing_init() -> anyhow::Result<()> {
31    let offset = time::UtcOffset::current_local_offset()?;
32    let timer = tracing_subscriber::fmt::time::OffsetTime::new(
33        offset,
34        time::macros::format_description!("[hour]:[minute]:[second].[subsecond digits:6]"),
35    );
36
37    // A filter consists of one or more comma-separated directives
38    // target[span{field=value}]=level
39    // Levels order: 1. ERROR, 2. WARN, 3. INFO, 4. DEBUG, 5. TRACE
40    // ERROR level is always logged.
41    // Add filters to CARGO_AUTO_LOG environment variable for a single execution:
42    // ```bash
43    // CARGO_AUTO_LOG="debug,hyper_util=info,reqwest=info" ./{package_name}
44    // ```
45    let filter = tracing_subscriber::EnvFilter::from_env("CARGO_AUTO_LOG");
46
47    let builder = tracing_subscriber::fmt()
48        .with_file(true)
49        .with_timer(timer)
50        .with_line_number(true)
51        .with_ansi(false)
52        .with_env_filter(filter);
53    if std::env::var("CARGO_AUTO_LOG").is_ok() {
54        // if CARGO_AUTO_LOG exists than enable tracing to file
55        let file_appender = tracing_appender::rolling::RollingFileAppender::builder()
56            .rotation(tracing_appender::rolling::Rotation::DAILY)
57            .filename_prefix("cargo_auto")
58            .filename_suffix("log")
59            .build("logs")
60            .expect("initializing rolling file appender failed");
61        builder.with_writer(file_appender).init();
62    } else {
63        builder.init();
64    };
65
66    Ok(())
67}