1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use crate::runtimeapi::wapc::log;
use log::{error, Level, LevelFilter, Metadata, Record};
use std::panic;

/// Logger used for runtime purposes
///
/// Default to the Info level.
///
static LOGGER: RuntimeLogger = RuntimeLogger {
    level: Level::Trace,
};

struct RuntimeLogger {
    level: Level,
}

/// Use the log crate for internal logging, and contract logging
///
/// following the example at https://docs.rs/log/0.4.8/log/fn.set_logger.html
impl log::Log for RuntimeLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            log(&format!("{} - {}", record.level(), record.args())[..]);
        }
    }

    fn flush(&self) {}
}

/// Called from the register contract macro.
///
/// Initalize the settings of the logger etc.
pub fn init_logger() {
    log::set_logger(&LOGGER).unwrap();
    log::set_max_level(LevelFilter::Trace);

    // configure the panic hook, otherwise any panics
    // when running in Wasm will be lost
    panic::set_hook(Box::new(hook));
}

/// Hook function to capture the panic and route it
/// to the logger
pub fn hook(info: &panic::PanicInfo) {
    let msg = info.to_string();

    // Finally, log the panic via waPC
    error!("[Panic]{}[/Panic]", msg);
}