subsoil/runtime/runtime_logger.rs
1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! A logger that can be used to log from the runtime.
8//!
9//! See [`RuntimeLogger`] for more docs.
10
11/// Runtime logger implementation - `log` crate backend.
12///
13/// The logger should be initialized if you want to display
14/// logs inside the runtime that is not necessarily running natively.
15pub struct RuntimeLogger;
16
17impl RuntimeLogger {
18 /// Initialize the logger.
19 ///
20 /// This is a no-op when running natively (`std`).
21 #[cfg(feature = "std")]
22 pub fn init() {}
23
24 /// Initialize the logger.
25 ///
26 /// This is a no-op when running natively (`std`).
27 #[cfg(not(feature = "std"))]
28 pub fn init() {
29 static LOGGER: RuntimeLogger = RuntimeLogger;
30 let _ = log::set_logger(&LOGGER);
31
32 // Use the same max log level as used by the host.
33 log::set_max_level(crate::io::logging::max_level().into());
34 }
35}
36
37impl log::Log for RuntimeLogger {
38 fn enabled(&self, _: &log::Metadata) -> bool {
39 // The final filtering is done by the host. This is not perfect, as we would still call into
40 // the host for log lines that will be thrown away.
41 true
42 }
43
44 fn log(&self, record: &log::Record) {
45 use ::core::fmt::Write;
46 let mut msg = alloc::string::String::default();
47 let _ = ::core::write!(&mut msg, "{}", record.args());
48
49 crate::io::logging::log(record.level().into(), record.target(), msg.as_bytes());
50 }
51
52 fn flush(&self) {}
53}
54
55// NOTE: runtime_logger integration test moved out of subsoil to avoid circular dev-dependency:
56// subsoil (dev-dep) -> soil-test-node-runtime-client -> soil-test-node-runtime -> subsoil (WASM)
57// This creates two compilations of subsoil with different features, causing trait mismatches.