1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 chromium::import! {
6 "//base:logging_log_severity_bindgen" as log_severity;
7 "//base:logging_rust_log_integration_bindgen" as rust_log_integration;
8 }
9
10 use log::Level::{Debug, Error, Info, Trace, Warn};
11 use log::{LevelFilter, Metadata, Record};
12 use log_severity::logging::{LOGGING_ERROR, LOGGING_INFO, LOGGING_WARNING};
13 use rust_log_integration::logging::internal::print_rust_log;
14 use std::ffi::CString;
15
16 struct RustLogger;
17
18 impl log::Log for RustLogger {
enabled(&self, _metadata: &Metadata) -> bool19 fn enabled(&self, _metadata: &Metadata) -> bool {
20 // Always enabled, as it's controlled by command line flags managed by the C++
21 // implementation.
22 true
23 }
24
log(&self, record: &Record)25 fn log(&self, record: &Record) {
26 // TODO(thiruak1024@gmail.com): Rather than using heap allocation to pass |msg|
27 // and |file|, we should return a pointer and size object to leverage the
28 // string_view object in C++. https://crbug.com/371112531
29 let msg = match record.args().as_str() {
30 Some(s) => CString::new(s),
31 None => CString::new(&*record.args().to_string()),
32 }
33 .expect("CString::new failed to create the log message!");
34 let file = CString::new(record.file().unwrap())
35 .expect("CString::new failed to create the log file name!");
36 unsafe {
37 print_rust_log(
38 msg.as_ptr(),
39 file.as_ptr(),
40 record.line().unwrap() as i32,
41 match record.metadata().level() {
42 Error => LOGGING_ERROR,
43 Warn => LOGGING_WARNING,
44 Info => LOGGING_INFO,
45 // Note that Debug and Trace level logs are dropped at
46 // compile time at the macro call-site when DCHECK_IS_ON()
47 // is false. This is done through a Cargo feature.
48 Debug | Trace => LOGGING_INFO,
49 },
50 record.metadata().level() == Trace,
51 )
52 }
53 }
flush(&self)54 fn flush(&self) {}
55 }
56
57 static RUST_LOGGER: RustLogger = RustLogger;
58
59 #[cxx::bridge(namespace = "logging::internal")]
60 mod ffi {
61 extern "Rust" {
init_rust_log_crate()62 fn init_rust_log_crate();
63 }
64 }
65
init_rust_log_crate()66 pub fn init_rust_log_crate() {
67 // An error may occur if set_logger has already been called, which can happen
68 // during unit tests. In that case, return from the method without executing the
69 // subsequent code.
70 if let Err(_) = log::set_logger(&RUST_LOGGER) {
71 return;
72 };
73 log::set_max_level(LevelFilter::Trace);
74 }
75