nautilus_common/ffi/
logging.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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::{
17    ffi::c_char,
18    ops::{Deref, DerefMut},
19};
20
21use ahash::AHashMap;
22use nautilus_core::{
23    UUID4,
24    ffi::{
25        parsing::{optional_bytes_to_json, u8_as_bool},
26        string::{cstr_as_str, cstr_to_ustr, optional_cstr_to_str},
27    },
28};
29use nautilus_model::identifiers::TraderId;
30
31use crate::{
32    enums::{LogColor, LogLevel},
33    logging::{
34        headers, init_logging,
35        logger::{self, LogGuard, LoggerConfig},
36        map_log_level_to_filter, parse_component_levels,
37        writer::FileWriterConfig,
38    },
39};
40
41/// C compatible Foreign Function Interface (FFI) for an underlying [`LogGuard`].
42///
43/// This struct wraps `LogGuard` in a way that makes it compatible with C function
44/// calls, enabling interaction with `LogGuard` in a C environment.
45///
46/// It implements the `Deref` trait, allowing instances of `LogGuard_API` to be
47/// dereferenced to `LogGuard`, providing access to `LogGuard`'s methods without
48/// having to manually access the underlying `LogGuard` instance.
49#[repr(C)]
50#[derive(Debug)]
51#[allow(non_camel_case_types)]
52pub struct LogGuard_API(Box<LogGuard>);
53
54impl Deref for LogGuard_API {
55    type Target = LogGuard;
56
57    fn deref(&self) -> &Self::Target {
58        &self.0
59    }
60}
61
62impl DerefMut for LogGuard_API {
63    fn deref_mut(&mut self) -> &mut Self::Target {
64        &mut self.0
65    }
66}
67
68/// Initializes logging.
69///
70/// Logging should be used for Python and sync Rust logic which is most of
71/// the components in the [nautilus_trader](https://pypi.org/project/nautilus_trader) package.
72/// Logging can be configured to filter components and write up to a specific level only
73/// by passing a configuration using the `NAUTILUS_LOG` environment variable.
74///
75/// # Safety
76///
77/// Should only be called once during an application's run, ideally at the
78/// beginning of the run.
79///
80/// This function assumes:
81/// - `directory_ptr` is either NULL or a valid C string pointer.
82/// - `file_name_ptr` is either NULL or a valid C string pointer.
83/// - `file_format_ptr` is either NULL or a valid C string pointer.
84/// - `component_level_ptr` is either NULL or a valid C string pointer.
85///
86/// # Panics
87///
88/// Panics if initializing the Rust logger fails.
89#[unsafe(no_mangle)]
90pub unsafe extern "C" fn logging_init(
91    trader_id: TraderId,
92    instance_id: UUID4,
93    level_stdout: LogLevel,
94    level_file: LogLevel,
95    directory_ptr: *const c_char,
96    file_name_ptr: *const c_char,
97    file_format_ptr: *const c_char,
98    component_levels_ptr: *const c_char,
99    is_colored: u8,
100    is_bypassed: u8,
101    print_config: u8,
102    log_components_only: u8,
103    max_file_size: u64,
104    max_backup_count: u32,
105) -> LogGuard_API {
106    let level_stdout = map_log_level_to_filter(level_stdout);
107    let level_file = map_log_level_to_filter(level_file);
108
109    let component_levels_json = unsafe { optional_bytes_to_json(component_levels_ptr) };
110    let component_levels = parse_component_levels(component_levels_json)
111        .expect("Failed to parse component log levels");
112
113    let config = LoggerConfig::new(
114        level_stdout,
115        level_file,
116        component_levels,
117        AHashMap::new(), // module_level - not exposed to FFI
118        u8_as_bool(log_components_only),
119        u8_as_bool(is_colored),
120        u8_as_bool(print_config),
121    );
122
123    // Configure file rotation if max_file_size > 0
124    let file_rotate = if max_file_size > 0 {
125        Some((max_file_size, max_backup_count))
126    } else {
127        None
128    };
129
130    let directory = unsafe { optional_cstr_to_str(directory_ptr).map(ToString::to_string) };
131    let file_name = unsafe { optional_cstr_to_str(file_name_ptr).map(ToString::to_string) };
132    let file_format = unsafe { optional_cstr_to_str(file_format_ptr).map(ToString::to_string) };
133
134    let file_config = FileWriterConfig::new(directory, file_name, file_format, file_rotate);
135
136    if u8_as_bool(is_bypassed) {
137        logging_set_bypass();
138    }
139
140    LogGuard_API(Box::new(
141        init_logging(trader_id, instance_id, config, file_config)
142            .expect("Failed to initialize logging"),
143    ))
144}
145
146/// Creates a new log event.
147///
148/// # Safety
149///
150/// This function assumes:
151/// - `component_ptr` is a valid C string pointer.
152/// - `message_ptr` is a valid C string pointer.
153#[unsafe(no_mangle)]
154pub unsafe extern "C" fn logger_log(
155    level: LogLevel,
156    color: LogColor,
157    component_ptr: *const c_char,
158    message_ptr: *const c_char,
159) {
160    let component = unsafe { cstr_to_ustr(component_ptr) };
161    let message = unsafe { cstr_as_str(message_ptr) };
162
163    logger::log(level, color, component, message);
164}
165
166/// Logs the Nautilus system header.
167///
168/// # Safety
169///
170/// This function assumes:
171/// - `machine_id_ptr` is a valid C string pointer.
172/// - `component_ptr` is a valid C string pointer.
173#[unsafe(no_mangle)]
174pub unsafe extern "C" fn logging_log_header(
175    trader_id: TraderId,
176    machine_id_ptr: *const c_char,
177    instance_id: UUID4,
178    component_ptr: *const c_char,
179) {
180    let component = unsafe { cstr_to_ustr(component_ptr) };
181    let machine_id = unsafe { cstr_as_str(machine_id_ptr) };
182    headers::log_header(trader_id, machine_id, instance_id, component);
183}
184
185/// Logs system information.
186///
187/// # Safety
188///
189/// Assumes `component_ptr` is a valid C string pointer.
190#[unsafe(no_mangle)]
191pub unsafe extern "C" fn logging_log_sysinfo(component_ptr: *const c_char) {
192    let component = unsafe { cstr_to_ustr(component_ptr) };
193    headers::log_sysinfo(component);
194}
195
196/// Flushes global logger buffers of any records.
197#[unsafe(no_mangle)]
198pub extern "C" fn logger_flush() {
199    log::logger().flush();
200}
201
202/// Flushes global logger buffers of any records and then drops the logger.
203#[unsafe(no_mangle)]
204pub extern "C" fn logger_drop(log_guard: LogGuard_API) {
205    drop(log_guard);
206}
207
208#[unsafe(no_mangle)]
209pub extern "C" fn logging_is_initialized() -> u8 {
210    u8::from(crate::logging::logging_is_initialized())
211}
212
213#[unsafe(no_mangle)]
214pub extern "C" fn logging_set_bypass() {
215    crate::logging::logging_set_bypass();
216}
217
218#[unsafe(no_mangle)]
219pub extern "C" fn logging_shutdown() {
220    crate::logging::logging_shutdown();
221}
222
223#[unsafe(no_mangle)]
224pub extern "C" fn logging_is_colored() -> u8 {
225    u8::from(crate::logging::logging_is_colored())
226}
227
228#[unsafe(no_mangle)]
229pub extern "C" fn logging_clock_set_realtime_mode() {
230    crate::logging::logging_clock_set_realtime_mode();
231}
232
233#[unsafe(no_mangle)]
234pub extern "C" fn logging_clock_set_static_mode() {
235    crate::logging::logging_clock_set_static_mode();
236}
237
238#[unsafe(no_mangle)]
239pub extern "C" fn logging_clock_set_static_time(time_ns: u64) {
240    crate::logging::logging_clock_set_static_time(time_ns);
241}