Skip to main content

rustolio_utils/
tracing.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11pub fn init() {
12    #[cfg(target_arch = "wasm32")]
13    {
14        let mut config = wasm_tracing::WasmLayerConfig::new();
15        config
16            .set_console_config(wasm_tracing::ConsoleConfig::ReportWithConsoleColor)
17            .set_show_origin(true)
18            .set_show_fields(true)
19            .set_report_logs_in_timings(true)
20            // .set_origin_base_url(impl ToString)
21            .set_max_level(get_level(option_env!("WASM_LOG")));
22        console_error_panic_hook::set_once();
23        wasm_tracing::set_as_global_default_with_config(config)
24            .expect("Failed to init `wasm_tracing`");
25    }
26
27    #[cfg(not(target_arch = "wasm32"))]
28    tracing_subscriber::fmt()
29        .with_file(cfg!(debug_assertions))
30        .with_line_number(cfg!(debug_assertions))
31        .with_target(true)
32        .with_level(true)
33        .with_max_level(get_level(std::env::var("RUST_LOG").ok()))
34        .init();
35}
36
37#[cfg(debug_assertions)]
38const DEFAULT_LEVEL: tracing::Level = tracing::Level::DEBUG;
39#[cfg(not(debug_assertions))]
40const DEFAULT_LEVEL: tracing::Level = tracing::Level::INFO;
41
42fn get_level(from: Option<impl ToString>) -> tracing::Level {
43    let Some(from) = from else {
44        return DEFAULT_LEVEL;
45    };
46    match from.to_string().to_uppercase().as_str() {
47        "TRACE" => tracing::Level::TRACE,
48        "DEBUG" => tracing::Level::DEBUG,
49        "INFO" => tracing::Level::INFO,
50        "WARN" => tracing::Level::WARN,
51        "ERROR" => tracing::Level::ERROR,
52        _ => DEFAULT_LEVEL,
53    }
54}