1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Rust `tracing` and Python `logging` setup and utilities.

use std::{path::PathBuf, str::FromStr};

use pyo3::prelude::*;
#[cfg(not(test))]
use tracing::span;
use tracing::Level;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{
    fmt::{self, writer::MakeWriterExt},
    layer::SubscriberExt,
    util::SubscriberInitExt,
    Layer,
};

use crate::error::PyException;

#[derive(Debug, Default)]
enum Format {
    Json,
    Pretty,
    #[default]
    Compact,
}

#[derive(Debug, PartialEq, Eq)]
struct InvalidFormatError;

impl FromStr for Format {
    type Err = InvalidFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "pretty" => Ok(Self::Pretty),
            "json" => Ok(Self::Json),
            "compact" => Ok(Self::Compact),
            _ => Err(InvalidFormatError),
        }
    }
}

/// Setup tracing-subscriber to log on console or to a hourly rolling file.
fn setup_tracing_subscriber(
    level: Option<u8>,
    logfile: Option<PathBuf>,
    format: Option<String>,
) -> PyResult<Option<WorkerGuard>> {
    let format = match format {
        Some(format) => Format::from_str(&format).unwrap_or_else(|_| {
            tracing::error!("unknown format '{format}', falling back to default formatter");
            Format::default()
        }),
        None => Format::default(),
    };

    let appender = match logfile {
        Some(logfile) => {
            let parent = logfile.parent().ok_or_else(|| {
                PyException::new_err(format!(
                    "Tracing setup failed: unable to extract dirname from path {}",
                    logfile.display()
                ))
            })?;
            let filename = logfile.file_name().ok_or_else(|| {
                PyException::new_err(format!(
                    "Tracing setup failed: unable to extract basename from path {}",
                    logfile.display()
                ))
            })?;
            let file_appender = tracing_appender::rolling::hourly(parent, filename);
            let (appender, guard) = tracing_appender::non_blocking(file_appender);
            Some((appender, guard))
        }
        None => None,
    };

    let tracing_level = match level {
        Some(40u8) => Level::ERROR,
        Some(30u8) => Level::WARN,
        Some(20u8) => Level::INFO,
        Some(10u8) => Level::DEBUG,
        None => Level::INFO,
        _ => Level::TRACE,
    };

    let formatter = fmt::Layer::new().with_line_number(true).with_level(true);

    match appender {
        Some((appender, guard)) => {
            let formatter = formatter.with_writer(appender.with_max_level(tracing_level));
            let formatter = match format {
                Format::Json => formatter.json().boxed(),
                Format::Compact => formatter.compact().boxed(),
                Format::Pretty => formatter.pretty().boxed(),
            };
            tracing_subscriber::registry().with(formatter).init();
            Ok(Some(guard))
        }
        None => {
            let formatter = formatter.with_writer(std::io::stdout.with_max_level(tracing_level));
            let formatter = match format {
                Format::Json => formatter.json().boxed(),
                Format::Compact => formatter.compact().boxed(),
                Format::Pretty => formatter.pretty().boxed(),
            };
            tracing_subscriber::registry().with(formatter).init();
            Ok(None)
        }
    }
}

/// Modifies the Python `logging` module to deliver its log messages using [tracing::Subscriber] events.
///
/// To achieve this goal, the following changes are made to the module:
/// - A new builtin function `logging.py_tracing_event` transcodes `logging.LogRecord`s to `tracing::Event`s. This function
///   is not exported in `logging.__all__`, as it is not intended to be called directly.
/// - A new class `logging.TracingHandler` provides a `logging.Handler` that delivers all records to `python_tracing`.
///
/// :param level typing.Optional\[int\]:
/// :param logfile typing.Optional\[pathlib.Path\]:
/// :param format typing.Optional\[typing.Literal\['compact', 'pretty', 'json'\]\]:
/// :rtype None:
#[pyclass(name = "TracingHandler")]
#[pyo3(text_signature = "($self, level=None, logfile=None, format=None)")]
#[derive(Debug)]
pub struct PyTracingHandler {
    _guard: Option<WorkerGuard>,
}

#[pymethods]
impl PyTracingHandler {
    #[new]
    fn newpy(
        py: Python,
        level: Option<u8>,
        logfile: Option<PathBuf>,
        format: Option<String>,
    ) -> PyResult<Self> {
        let _guard = setup_tracing_subscriber(level, logfile, format)?;
        let logging = py.import("logging")?;
        let root = logging.getattr("root")?;
        root.setattr("level", level)?;
        // TODO(Investigate why the file appender just create the file and does not write anything, event after holding the guard)
        Ok(Self { _guard })
    }

    /// :rtype typing.Any:
    fn handler(&self, py: Python) -> PyResult<Py<PyAny>> {
        let logging = py.import("logging")?;
        logging.setattr(
            "py_tracing_event",
            wrap_pyfunction!(py_tracing_event, logging)?,
        )?;

        let pycode = r#"
class TracingHandler(Handler):
    """ Python logging to Rust tracing handler. """
    def emit(self, record):
        py_tracing_event(
            record.levelno, record.getMessage(), record.module,
            record.filename, record.lineno, record.process
        )
"#;
        py.run(pycode, Some(logging.dict()), None)?;
        let all = logging.index()?;
        all.append("TracingHandler")?;
        let handler = logging.getattr("TracingHandler")?;
        Ok(handler.call0()?.into_py(py))
    }
}

/// Consumes a Python `logging.LogRecord` and emits a Rust [tracing::Event] instead.
#[cfg(not(test))]
#[pyfunction]
#[pyo3(text_signature = "(level, record, message, module, filename, line, pid)")]
pub fn py_tracing_event(
    level: u8,
    message: &str,
    module: &str,
    filename: &str,
    lineno: usize,
    pid: usize,
) -> PyResult<()> {
    let span = span!(
        Level::TRACE,
        "python",
        pid = pid,
        module = module,
        filename = filename,
        lineno = lineno
    );
    let _guard = span.enter();
    match level {
        40 => tracing::error!("{message}"),
        30 => tracing::warn!("{message}"),
        20 => tracing::info!("{message}"),
        10 => tracing::debug!("{message}"),
        _ => tracing::trace!("{message}"),
    };
    Ok(())
}

#[cfg(test)]
#[pyfunction]
#[pyo3(text_signature = "(level, record, message, module, filename, line, pid)")]
pub fn py_tracing_event(
    _level: u8,
    message: &str,
    _module: &str,
    _filename: &str,
    _line: usize,
    _pid: usize,
) -> PyResult<()> {
    pretty_assertions::assert_eq!(message.to_string(), "a message");
    Ok(())
}

#[cfg(test)]
mod tests {
    use pyo3::types::PyDict;

    use super::*;

    #[test]
    fn tracing_handler_is_injected_in_python() {
        crate::tests::initialize();
        Python::with_gil(|py| {
            let handler = PyTracingHandler::newpy(py, Some(10), None, None).unwrap();
            let kwargs = PyDict::new(py);
            kwargs
                .set_item("handlers", vec![handler.handler(py).unwrap()])
                .unwrap();
            let logging = py.import("logging").unwrap();
            let basic_config = logging.getattr("basicConfig").unwrap();
            basic_config.call((), Some(kwargs)).unwrap();
            logging.call_method1("info", ("a message",)).unwrap();
        });
    }
}