about summary refs log tree commit diff stats
path: root/crates/yt_dlp/src/logging.rs
blob: 5cb4c1d06c68db101219a6ed4a36c8010f8126c1 (plain) (blame)
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

// This file is taken from: https://github.com/dylanbstorey/pyo3-pylogger/blob/d89e0d6820ebc4f067647e3b74af59dbc4941dd5/src/lib.rs
// It is licensed under the Apache 2.0 License, copyright up to 2024 by Dylan Storey
// It was modified by Benedikt Peetz 2024, 2025

use log::{Level, MetadataBuilder, Record, logger};
use rustpython::vm::{
    PyObjectRef, PyRef, PyResult, VirtualMachine,
    builtins::{PyInt, PyList, PyStr},
    convert::ToPyObject,
    function::FuncArgs,
};

/// Consume a Python `logging.LogRecord` and emit a Rust `Log` instead.
fn host_log(mut input: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
    let record = input.args.remove(0);
    let rust_target = {
        let base: PyRef<PyStr> = input.args.remove(0).downcast().expect("Should be a string");
        base.as_str().to_owned()
    };

    let level = {
        let level: PyRef<PyInt> = record
            .get_attr("levelno", vm)?
            .downcast()
            .expect("Should always be an int");
        level.as_u32_mask()
    };
    let message = {
        let get_message = record.get_attr("getMessage", vm)?;
        let message: PyRef<PyStr> = get_message
            .call((), vm)?
            .downcast()
            .expect("Downcasting works");

        message.as_str().to_owned()
    };

    let pathname = {
        let pathname: PyRef<PyStr> = record
            .get_attr("pathname", vm)?
            .downcast()
            .expect("Is a string");

        pathname.as_str().to_owned()
    };

    let lineno = {
        let lineno: PyRef<PyInt> = record
            .get_attr("lineno", vm)?
            .downcast()
            .expect("Is a number");

        lineno.as_u32_mask()
    };

    let logger_name = {
        let name: PyRef<PyStr> = record
            .get_attr("name", vm)?
            .downcast()
            .expect("Should be a string");
        name.as_str().to_owned()
    };

    let full_target: Option<String> = if logger_name.trim().is_empty() || logger_name == "root" {
        None
    } else {
        // Libraries (ex: tracing_subscriber::filter::Directive) expect rust-style targets like foo::bar,
        // and may not deal well with "." as a module separator:
        let logger_name = logger_name.replace('.', "::");
        Some(format!("{rust_target}::{logger_name}"))
    };

    let target = full_target.as_deref().unwrap_or(&rust_target);

    // error
    let error_metadata = if level >= 40 {
        MetadataBuilder::new()
            .target(target)
            .level(Level::Error)
            .build()
    } else if level >= 30 {
        MetadataBuilder::new()
            .target(target)
            .level(Level::Warn)
            .build()
    } else if level >= 20 {
        MetadataBuilder::new()
            .target(target)
            .level(Level::Info)
            .build()
    } else if level >= 10 {
        MetadataBuilder::new()
            .target(target)
            .level(Level::Debug)
            .build()
    } else {
        MetadataBuilder::new()
            .target(target)
            .level(Level::Trace)
            .build()
    };

    logger().log(
        &Record::builder()
            .metadata(error_metadata)
            .args(format_args!("{}", &message))
            .line(Some(lineno))
            .file(None)
            .module_path(Some(&pathname))
            .build(),
    );

    Ok(())
}

/// Registers the `host_log` function in rust as the event handler for Python's logging logger
/// This function needs to be called from within a pyo3 context as early as possible to ensure logging messages
/// arrive to the rust consumer.
///
/// # Panics
/// Only if internal assertions fail.
#[allow(clippy::module_name_repetitions)]
pub(super) fn setup_logging(vm: &VirtualMachine, target: &str) -> PyResult<PyObjectRef> {
    let logging = vm.import("logging", 0)?;

    let scope = vm.new_scope_with_builtins();

    for (key, value) in logging.dict().expect("Should be a dict") {
        let key: PyRef<PyStr> = key.downcast().expect("Is a string");

        scope.globals.set_item(key.as_str(), value, vm)?;
    }
    scope
        .globals
        .set_item("host_log", vm.new_function("host_log", host_log).into(), vm)?;

    let local_scope = scope.clone();
    vm.run_code_string(
        local_scope,
        format!(
            r#"
class HostHandler(Handler):
    def __init__(self, level=0):
        super().__init__(level=level)

    def emit(self, record):
        host_log(record,"{target}")

oldBasicConfig = basicConfig
def basicConfig(*pargs, **kwargs):
    if "handlers" not in kwargs:
        kwargs["handlers"] = [HostHandler()]
    return oldBasicConfig(*pargs, **kwargs)
"#
        )
        .as_str(),
        "<embedded logging inintializing code>".to_owned(),
    )?;

    let all: PyRef<PyList> = logging
        .get_attr("__all__", vm)?
        .downcast()
        .expect("Is a list");
    all.borrow_vec_mut().push(vm.new_pyobj("HostHandler"));

    // {
    //     let logging_dict = logging.dict().expect("Exists");
    //
    //     for (key, val) in scope.globals {
    //         let key: PyRef<PyStr> = key.downcast().expect("Is a string");
    //
    //         if !logging_dict.contains_key(key.as_str(), vm) {
    //             logging_dict.set_item(key.as_str(), val, vm)?;
    //         }
    //     }
    //
    //     for (key, val) in scope.locals {
    //         let key: PyRef<PyStr> = key.downcast().expect("Is a string");
    //
    //         if !logging_dict.contains_key(key.as_str(), vm) {
    //             logging_dict.set_item(key.as_str(), val, vm)?;
    //         }
    //     }
    // }

    Ok(scope.globals.to_pyobject(vm))
}