sp_runtime/
runtime_logger.rs1pub struct RuntimeLogger;
27
28impl RuntimeLogger {
29 #[cfg(feature = "std")]
33 pub fn init() {}
34
35 #[cfg(not(feature = "std"))]
39 pub fn init() {
40 static LOGGER: RuntimeLogger = RuntimeLogger;
41 let _ = log::set_logger(&LOGGER);
42
43 log::set_max_level(sp_io::logging::max_level().into());
45 }
46}
47
48impl log::Log for RuntimeLogger {
49 fn enabled(&self, _: &log::Metadata) -> bool {
50 true
53 }
54
55 fn log(&self, record: &log::Record) {
56 use core::fmt::Write;
57 let mut w = sp_std::Writer::default();
58 let _ = ::core::write!(&mut w, "{}", record.args());
59
60 sp_io::logging::log(record.level().into(), record.target(), w.inner());
61 }
62
63 fn flush(&self) {}
64}
65
66#[cfg(test)]
67mod tests {
68 use sp_api::ProvideRuntimeApi;
69 use std::env;
70 use substrate_test_runtime_client::{
71 runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt,
72 };
73
74 #[test]
75 fn ensure_runtime_logger_works() {
76 if env::var("RUN_TEST").is_ok() {
77 sp_tracing::try_init_simple();
78
79 let client = TestClientBuilder::new().build();
80 let runtime_api = client.runtime_api();
81 runtime_api
82 .do_trace_log(client.chain_info().genesis_hash)
83 .expect("Logging should not fail");
84 } else {
85 for (level, should_print) in &[("test=trace", true), ("info", false)] {
86 let executable = std::env::current_exe().unwrap();
87 let output = std::process::Command::new(executable)
88 .env("RUN_TEST", "1")
89 .env("RUST_LOG", level)
90 .args(&["--nocapture", "ensure_runtime_logger_works"])
91 .output()
92 .unwrap();
93
94 let output = String::from_utf8(output.stderr).unwrap();
95 assert!(output.contains("Hey I'm runtime") == *should_print);
96 assert!(output.contains("THIS IS TRACING") == *should_print);
97 assert!(output.contains("Hey, I'm tracing") == *should_print);
98 }
99 }
100 }
101}