问题描述
我想使用到 console.log 的消息进行调试。
我们有一个 rust wasm32-wasi 函数被在 nodejs 中运行的 javascript 调用。由于其他限制,我们无法使用 ssvm/ssvmup。
我们可以做些什么来在控制台中查看来自我们 wasm 代码的消息吗?
解决方法
这在 The wasm-bindgen Guide: Using console.log 中得到了回答:
-
方法#1,手动绑定:
#[wasm_bindgen] extern "C" { // Use `js_namespace` here to bind `console.log(..)` instead of just // `log(..)` #[wasm_bindgen(js_namespace = console)] fn log(s: &str); // The `console.log` is quite polymorphic,so we can bind it with multiple // signatures. Note that we need to use `js_name` to ensure we always call // `log` in JS. #[wasm_bindgen(js_namespace = console,js_name = log)] fn log_u32(a: u32); // Multiple arguments too! #[wasm_bindgen(js_namespace = console,js_name = log)] fn log_many(a: &str,b: &str); } fn bare_bones() { log("Hello from Rust!"); log_u32(42); log_many("Logging","many values!"); }
-
方法 #2,使用
web-sys
板条箱:fn using_web_sys() { use web_sys::console; console::log_1(&"Hello using web-sys".into()); let js: JsValue = 4.into(); console::log_2(&"Logging arbitrary values looks like".into(),&js); }
另一种可能的替代方案,如果您要进行大量日志记录,您可能需要考虑使用 log
板条箱和 wasm-logger
门面:
wasm_logger::init(wasm_logger::Config::default());
// Logging
log::info!("Some info");
log::error!("Error message");