sp_runtime/
runtime_logger.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! A logger that can be used to log from the runtime.
19//!
20//! See [`RuntimeLogger`] for more docs.
21
22/// Runtime logger implementation - `log` crate backend.
23///
24/// The logger should be initialized if you want to display
25/// logs inside the runtime that is not necessarily running natively.
26pub struct RuntimeLogger;
27
28impl RuntimeLogger {
29	/// Initialize the logger.
30	///
31	/// This is a no-op when running natively (`std`).
32	#[cfg(feature = "std")]
33	pub fn init() {}
34
35	/// Initialize the logger.
36	///
37	/// This is a no-op when running natively (`std`).
38	#[cfg(not(feature = "std"))]
39	pub fn init() {
40		static LOGGER: RuntimeLogger = RuntimeLogger;
41		let _ = log::set_logger(&LOGGER);
42
43		// Use the same max log level as used by the host.
44		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		// The final filtering is done by the host. This is not perfect, as we would still call into
51		// the host for log lines that will be thrown away.
52		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}