nautilus_common/logging/
mod.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
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
16//! The logging framework for Nautilus systems.
17
18pub mod headers;
19pub mod logger;
20pub mod writer;
21
22use std::{
23    collections::HashMap,
24    env,
25    str::FromStr,
26    sync::atomic::{AtomicBool, Ordering},
27};
28
29use log::LevelFilter;
30use nautilus_core::{UUID4, time::get_atomic_clock_static};
31use nautilus_model::identifiers::TraderId;
32use tracing_subscriber::EnvFilter;
33use ustr::Ustr;
34
35use self::{
36    logger::{LogGuard, Logger, LoggerConfig},
37    writer::FileWriterConfig,
38};
39use crate::enums::LogLevel;
40
41pub const RECV: &str = "<--";
42pub const SEND: &str = "-->";
43pub const CMD: &str = "[CMD]";
44pub const EVT: &str = "[EVT]";
45pub const DOC: &str = "[DOC]";
46pub const RPT: &str = "[RPT]";
47pub const REQ: &str = "[REQ]";
48pub const RES: &str = "[RES]";
49
50static LOGGING_INITIALIZED: AtomicBool = AtomicBool::new(false);
51static LOGGING_BYPASSED: AtomicBool = AtomicBool::new(false);
52static LOGGING_REALTIME: AtomicBool = AtomicBool::new(true);
53static LOGGING_COLORED: AtomicBool = AtomicBool::new(true);
54
55/// Returns whether the core logger is enabled.
56#[unsafe(no_mangle)]
57pub extern "C" fn logging_is_initialized() -> u8 {
58    u8::from(LOGGING_INITIALIZED.load(Ordering::Relaxed))
59}
60
61/// Sets the logging system to bypass mode.
62#[unsafe(no_mangle)]
63pub extern "C" fn logging_set_bypass() {
64    LOGGING_BYPASSED.store(true, Ordering::Relaxed);
65}
66
67/// Shuts down the logging system.
68#[unsafe(no_mangle)]
69pub extern "C" fn logging_shutdown() {
70    // Flush any buffered logs and mark logging as uninitialized
71    log::logger().flush();
72    LOGGING_INITIALIZED.store(false, Ordering::Relaxed);
73}
74
75/// Returns whether the core logger is using ANSI colors.
76#[unsafe(no_mangle)]
77pub extern "C" fn logging_is_colored() -> u8 {
78    u8::from(LOGGING_COLORED.load(Ordering::Relaxed))
79}
80
81/// Sets the global logging clock to real-time mode.
82#[unsafe(no_mangle)]
83pub extern "C" fn logging_clock_set_realtime_mode() {
84    LOGGING_REALTIME.store(true, Ordering::Relaxed);
85}
86
87/// Sets the global logging clock to static mode.
88#[unsafe(no_mangle)]
89pub extern "C" fn logging_clock_set_static_mode() {
90    LOGGING_REALTIME.store(false, Ordering::Relaxed);
91}
92
93/// Sets the global logging clock static time with the given UNIX timestamp (nanoseconds).
94#[unsafe(no_mangle)]
95pub extern "C" fn logging_clock_set_static_time(time_ns: u64) {
96    let clock = get_atomic_clock_static();
97    clock.set_time(time_ns.into());
98}
99
100/// Initialize tracing.
101///
102/// Tracing is meant to be used to trace/debug async Rust code. It can be
103/// configured to filter modules and write up to a specific level by passing
104/// a configuration using the `RUST_LOG` environment variable.
105///
106/// # Safety
107///
108/// Should only be called once during an applications run, ideally at the
109/// beginning of the run.
110///
111/// # Errors
112///
113/// Returns an error if tracing subscriber fails to initialize.
114pub fn init_tracing() -> anyhow::Result<()> {
115    // Skip tracing initialization if `RUST_LOG` is not set
116    if let Ok(v) = env::var("RUST_LOG") {
117        let env_filter = EnvFilter::new(v.clone());
118
119        tracing_subscriber::fmt()
120            .with_env_filter(env_filter)
121            .try_init()
122            .map_err(|e| anyhow::anyhow!("Failed to initialize tracing subscriber: {e}"))?;
123
124        println!("Initialized tracing logs with RUST_LOG={v}");
125    }
126    Ok(())
127}
128
129/// Initialize logging.
130///
131/// Logging should be used for Python and sync Rust logic which is most of
132/// the components in the [nautilus_trader](https://pypi.org/project/nautilus_trader) package.
133/// Logging can be configured to filter components and write up to a specific level only
134/// by passing a configuration using the `NAUTILUS_LOG` environment variable.
135///
136/// # Safety
137///
138/// Should only be called once during an applications run, ideally at the
139/// beginning of the run.
140pub fn init_logging(
141    trader_id: TraderId,
142    instance_id: UUID4,
143    config: LoggerConfig,
144    file_config: FileWriterConfig,
145) -> anyhow::Result<LogGuard> {
146    LOGGING_INITIALIZED.store(true, Ordering::Relaxed);
147    LOGGING_COLORED.store(config.is_colored, Ordering::Relaxed);
148    Logger::init_with_config(trader_id, instance_id, config, file_config)
149}
150
151#[must_use]
152pub const fn map_log_level_to_filter(log_level: LogLevel) -> LevelFilter {
153    match log_level {
154        LogLevel::Off => LevelFilter::Off,
155        LogLevel::Trace => LevelFilter::Trace,
156        LogLevel::Debug => LevelFilter::Debug,
157        LogLevel::Info => LevelFilter::Info,
158        LogLevel::Warning => LevelFilter::Warn,
159        LogLevel::Error => LevelFilter::Error,
160    }
161}
162
163#[must_use]
164pub fn parse_level_filter_str(s: &str) -> LevelFilter {
165    let mut log_level_str = s.to_string().to_uppercase();
166    if log_level_str == "WARNING" {
167        log_level_str = "WARN".to_string();
168    }
169    LevelFilter::from_str(&log_level_str)
170        .unwrap_or_else(|_| panic!("Invalid `LevelFilter` string, was {log_level_str}"))
171}
172
173#[must_use]
174pub fn parse_component_levels(
175    original_map: Option<HashMap<String, serde_json::Value>>,
176) -> HashMap<Ustr, LevelFilter> {
177    match original_map {
178        Some(map) => {
179            let mut new_map = HashMap::new();
180            for (key, value) in map {
181                let ustr_key = Ustr::from(&key);
182                // Expect the JSON value to be a string representing a log level
183                let s = value
184                    .as_str()
185                    .expect("Invalid component log level: expected string");
186                let lvl = parse_level_filter_str(s);
187                new_map.insert(ustr_key, lvl);
188            }
189            new_map
190        }
191        None => HashMap::new(),
192    }
193}