nautilus_common/python/
logging.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
16use std::collections::HashMap;
17
18use log::LevelFilter;
19use nautilus_core::{UUID4, python::to_pyvalue_err};
20use nautilus_model::identifiers::TraderId;
21use pyo3::prelude::*;
22use ustr::Ustr;
23
24use crate::{
25    enums::{LogColor, LogLevel},
26    logging::{
27        self, headers,
28        logger::{self, LogGuard, LoggerConfig},
29        logging_clock_set_realtime_mode, logging_clock_set_static_mode,
30        logging_clock_set_static_time, logging_set_bypass, map_log_level_to_filter,
31        parse_level_filter_str,
32        writer::FileWriterConfig,
33    },
34};
35
36#[pymethods]
37impl LoggerConfig {
38    /// Creates a [`LoggerConfig`] from a spec string.
39    ///
40    /// # Errors
41    ///
42    /// Returns a Python exception if the spec string is invalid.
43    #[staticmethod]
44    #[pyo3(name = "from_spec")]
45    pub fn py_from_spec(spec: String) -> PyResult<Self> {
46        Self::from_spec(&spec).map_err(to_pyvalue_err)
47    }
48}
49
50#[pymethods]
51impl FileWriterConfig {
52    #[new]
53    #[pyo3(signature = (directory=None, file_name=None, file_format=None, file_rotate=None))]
54    #[must_use]
55    pub fn py_new(
56        directory: Option<String>,
57        file_name: Option<String>,
58        file_format: Option<String>,
59        file_rotate: Option<(u64, u32)>,
60    ) -> Self {
61        Self::new(directory, file_name, file_format, file_rotate)
62    }
63}
64
65/// Initialize tracing.
66///
67/// Tracing is meant to be used to trace/debug async Rust code. It can be
68/// configured to filter modules and write up to a specific level only using
69/// by passing a configuration using the `RUST_LOG` environment variable.
70///
71/// # Safety
72///
73/// Should only be called once during an applications run, ideally at the
74/// beginning of the run.
75///
76/// # Errors
77///
78/// Returns an error if tracing subscriber fails to initialize.
79#[pyfunction()]
80#[pyo3(name = "init_tracing")]
81pub fn py_init_tracing() -> PyResult<()> {
82    logging::init_tracing().map_err(to_pyvalue_err)
83}
84
85/// Initialize logging.
86///
87/// Logging should be used for Python and sync Rust logic which is most of
88/// the components in the [nautilus_trader](https://pypi.org/project/nautilus_trader) package.
89/// Logging can be configured to filter components and write up to a specific level only
90/// by passing a configuration using the `NAUTILUS_LOG` environment variable.
91///
92/// # Safety
93///
94/// Should only be called once during an applications run, ideally at the
95/// beginning of the run.
96/// Initializes logging via Python interface.
97///
98/// # Errors
99///
100/// Returns a Python exception if logger initialization fails.
101#[pyfunction]
102#[pyo3(name = "init_logging")]
103#[allow(clippy::too_many_arguments)]
104#[pyo3(signature = (trader_id, instance_id, level_stdout, level_file=None, component_levels=None, directory=None, file_name=None, file_format=None, file_rotate=None, is_colored=None, is_bypassed=None, print_config=None))]
105pub fn py_init_logging(
106    trader_id: TraderId,
107    instance_id: UUID4,
108    level_stdout: LogLevel,
109    level_file: Option<LogLevel>,
110    component_levels: Option<HashMap<String, String>>,
111    directory: Option<String>,
112    file_name: Option<String>,
113    file_format: Option<String>,
114    file_rotate: Option<(u64, u32)>,
115    is_colored: Option<bool>,
116    is_bypassed: Option<bool>,
117    print_config: Option<bool>,
118) -> PyResult<LogGuard> {
119    let level_file = level_file.map_or(LevelFilter::Off, map_log_level_to_filter);
120
121    let config = LoggerConfig::new(
122        map_log_level_to_filter(level_stdout),
123        level_file,
124        parse_component_levels(component_levels),
125        is_colored.unwrap_or(true),
126        print_config.unwrap_or(false),
127    );
128
129    let file_config = FileWriterConfig::new(directory, file_name, file_format, file_rotate);
130
131    if is_bypassed.unwrap_or(false) {
132        logging_set_bypass();
133    }
134
135    logging::init_logging(trader_id, instance_id, config, file_config).map_err(to_pyvalue_err)
136}
137
138#[pyfunction()]
139#[pyo3(name = "logger_flush")]
140pub fn py_logger_flush() {
141    log::logger().flush()
142}
143
144fn parse_component_levels(
145    original_map: Option<HashMap<String, String>>,
146) -> HashMap<Ustr, LevelFilter> {
147    match original_map {
148        Some(map) => {
149            let mut new_map = HashMap::new();
150            for (key, value) in map {
151                let ustr_key = Ustr::from(&key);
152                let value = parse_level_filter_str(&value);
153                new_map.insert(ustr_key, value);
154            }
155            new_map
156        }
157        None => HashMap::new(),
158    }
159}
160
161/// Create a new log event.
162#[pyfunction]
163#[pyo3(name = "logger_log")]
164pub fn py_logger_log(level: LogLevel, color: LogColor, component: &str, message: &str) {
165    logger::log(level, color, Ustr::from(component), message);
166}
167
168/// Logs the standard Nautilus system header.
169#[pyfunction]
170#[pyo3(name = "log_header")]
171pub fn py_log_header(trader_id: TraderId, machine_id: &str, instance_id: UUID4, component: &str) {
172    headers::log_header(trader_id, machine_id, instance_id, Ustr::from(component));
173}
174
175/// Logs system information.
176#[pyfunction]
177#[pyo3(name = "log_sysinfo")]
178pub fn py_log_sysinfo(component: &str) {
179    headers::log_sysinfo(Ustr::from(component));
180}
181
182#[pyfunction]
183#[pyo3(name = "logging_clock_set_static_mode")]
184pub fn py_logging_clock_set_static_mode() {
185    logging_clock_set_static_mode();
186}
187
188#[pyfunction]
189#[pyo3(name = "logging_clock_set_realtime_mode")]
190pub fn py_logging_clock_set_realtime_mode() {
191    logging_clock_set_realtime_mode();
192}
193
194#[pyfunction]
195#[pyo3(name = "logging_clock_set_static_time")]
196pub fn py_logging_clock_set_static_time(time_ns: u64) {
197    logging_clock_set_static_time(time_ns);
198}
199
200/// A thin wrapper around the global Rust logger which exposes ergonomic
201/// logging helpers for Python code.
202///
203/// It mirrors the familiar Python `logging` interface while forwarding
204/// all records through the Nautilus logging infrastructure so that log levels
205/// and formatting remain consistent across Rust and Python.
206#[pyclass(
207    module = "nautilus_trader.core.nautilus_pyo3.common",
208    name = "Logger",
209    unsendable
210)]
211#[derive(Debug, Clone)]
212pub struct PyLogger {
213    name: Ustr,
214}
215
216impl PyLogger {
217    pub fn new(name: &str) -> Self {
218        Self {
219            name: Ustr::from(name),
220        }
221    }
222}
223
224#[pymethods]
225impl PyLogger {
226    /// Create a new `Logger` instance.
227    #[new]
228    #[pyo3(signature = (name="Python"))]
229    fn py_new(name: &str) -> Self {
230        Self::new(name)
231    }
232
233    /// The component identifier carried by this logger.
234    #[getter]
235    fn name(&self) -> &str {
236        &self.name
237    }
238
239    /// Emit a TRACE level record.
240    #[pyo3(name = "trace")]
241    fn py_trace(&self, message: &str, color: Option<LogColor>) {
242        self._log(LogLevel::Trace, color, message);
243    }
244
245    /// Emit a DEBUG level record.
246    #[pyo3(name = "debug")]
247    fn py_debug(&self, message: &str, color: Option<LogColor>) {
248        self._log(LogLevel::Debug, color, message);
249    }
250
251    /// Emit an INFO level record.
252    #[pyo3(name = "info")]
253    fn py_info(&self, message: &str, color: Option<LogColor>) {
254        self._log(LogLevel::Info, color, message);
255    }
256
257    /// Emit a WARNING level record.
258    #[pyo3(name = "warning")]
259    fn py_warning(&self, message: &str, color: Option<LogColor>) {
260        self._log(LogLevel::Warning, color, message);
261    }
262
263    /// Emit an ERROR level record.
264    #[pyo3(name = "error")]
265    fn py_error(&self, message: &str, color: Option<LogColor>) {
266        self._log(LogLevel::Error, color, message);
267    }
268
269    /// Emit an ERROR level record with the active Python exception info.
270    #[pyo3(name = "exception")]
271    #[pyo3(signature = (message="", color=None))]
272    fn py_exception(&self, py: Python, message: &str, color: Option<LogColor>) {
273        let mut full_msg = message.to_owned();
274
275        if pyo3::PyErr::occurred(py) {
276            let err = PyErr::fetch(py);
277            let err_str = err.to_string();
278            if full_msg.is_empty() {
279                full_msg = err_str;
280            } else {
281                full_msg = format!("{full_msg}: {err_str}");
282            }
283        }
284
285        self._log(LogLevel::Error, color, &full_msg);
286    }
287
288    /// Flush buffered log records.
289    #[pyo3(name = "flush")]
290    fn py_flush(&self) {
291        log::logger().flush();
292    }
293
294    fn _log(&self, level: LogLevel, color: Option<LogColor>, message: &str) {
295        let color = color.unwrap_or(LogColor::Normal);
296        logger::log(level, color, self.name, message);
297    }
298}