wascc_actor/
logger.rs

1use crate::HandlerResult;
2use log::{Metadata, Record};
3use std::sync::{Arc, RwLock};
4use wapc_guest::host_call;
5use wascc_codec::logging::*;
6use wascc_codec::serialize;
7
8/// The reserved capability ID for the logging functionality
9pub const CAPID_LOGGING: &str = "wascc:logging";
10
11const ERROR: u32 = 1;
12const WARN: u32 = 2;
13const INFO: u32 = 3;
14const DEBUG: u32 = 4;
15const TRACE: u32 = 5;
16
17lazy_static! {
18    static ref CURRENT_BINDING: Arc<RwLock<String>> =
19        { Arc::new(RwLock::new("default".to_string())) };
20}
21
22static LOGGER: AutomaticLoggerHostBinding = AutomaticLoggerHostBinding {};
23
24#[allow(dead_code)]
25#[doc(hidden)]
26pub fn ensure_logger() {
27    match log::set_logger(&LOGGER) {
28        Ok(_) => {}
29        Err(_) => {}
30    }
31    log::set_max_level(log::LevelFilter::Trace);
32}
33
34/// A host binding for the wascc:logging capability
35pub struct AutomaticLoggerHostBinding {}
36
37impl Default for AutomaticLoggerHostBinding {
38    fn default() -> Self {
39        AutomaticLoggerHostBinding {}
40    }
41}
42
43fn set_binding(binding: &str) {
44    *CURRENT_BINDING.write().unwrap() = binding.to_string();
45}
46
47/// Sets the current binding for the logger. Note that because the logger
48/// is statically available in order to support Rust's `log` macros,
49/// the _msot recent binding_ you set is the one that will
50/// be active for your logging macros. You can't maintain two different logger
51/// bindings that send to two different host bindings, you must instead toggle
52/// between them.
53pub fn host(binding: &str) -> AutomaticLoggerHostBinding {
54    set_binding(binding);
55    AutomaticLoggerHostBinding {}
56}
57
58/// Resets the current logger binding name to the default.
59pub fn default() -> AutomaticLoggerHostBinding {
60    set_binding("default");
61    AutomaticLoggerHostBinding {}
62}
63
64impl log::Log for AutomaticLoggerHostBinding {
65    fn enabled(&self, _metadata: &Metadata) -> bool {
66        true
67    }
68
69    fn log(&self, record: &Record) {
70        if self.enabled(record.metadata()) {
71            let l = WriteLogRequest {
72                level: record.level() as _,
73                body: format!("{}", record.args()),
74            };
75            self._log(l)
76        }
77    }
78
79    fn flush(&self) {}
80}
81
82impl AutomaticLoggerHostBinding {
83    fn _log(&self, req: WriteLogRequest) {
84        let _ = host_call(
85            &CURRENT_BINDING.read().unwrap(),
86            CAPID_LOGGING,
87            OP_LOG,
88            &serialize(req).unwrap(),
89        );
90    }
91
92    /// Write a log entry on the host
93    pub fn log(&self, level: u32, body: &str) -> HandlerResult<()> {
94        let l = WriteLogRequest {
95            level: level,
96            body: body.to_string(),
97        };
98        let _ = host_call(
99            &CURRENT_BINDING.read().unwrap(),
100            CAPID_LOGGING,
101            OP_LOG,
102            &serialize(l)?,
103        );
104        Ok(())
105    }
106
107    /// Write a log entry at the error level. You should instead use the `error!` macro
108    pub fn error(&self, body: &str) -> HandlerResult<()> {
109        let l = WriteLogRequest {
110            level: ERROR,
111            body: body.to_string(),
112        };
113        let _ = host_call(
114            &CURRENT_BINDING.read().unwrap(),
115            CAPID_LOGGING,
116            OP_LOG,
117            &serialize(l)?,
118        );
119        Ok(())
120    }
121
122    /// Write a log entry at the warn level. You should instead use the `warn!` macro
123    pub fn warn(&self, body: &str) -> HandlerResult<()> {
124        let l = WriteLogRequest {
125            level: WARN,
126            body: body.to_string(),
127        };
128        let _ = host_call(
129            &CURRENT_BINDING.read().unwrap(),
130            CAPID_LOGGING,
131            OP_LOG,
132            &serialize(l)?,
133        );
134        Ok(())
135    }
136
137    /// Write a log entry at the info level. You should instead use the `info!` macro
138    pub fn info(&self, body: &str) -> HandlerResult<()> {
139        let l = WriteLogRequest {
140            level: INFO,
141            body: body.to_string(),
142        };
143        let _ = host_call(
144            &CURRENT_BINDING.read().unwrap(),
145            CAPID_LOGGING,
146            OP_LOG,
147            &serialize(l)?,
148        );
149        Ok(())
150    }
151
152    /// Write a log entry at the debug level. You should instead use the `debug!` macro
153    pub fn debug(&self, body: &str) -> HandlerResult<()> {
154        let l = WriteLogRequest {
155            level: DEBUG,
156            body: body.to_string(),
157        };
158        let _ = host_call(
159            &CURRENT_BINDING.read().unwrap(),
160            CAPID_LOGGING,
161            OP_LOG,
162            &serialize(l)?,
163        );
164        Ok(())
165    }
166
167    /// Write a log entry at the trace level. You should instead use the `trace!` macro
168    pub fn trace(&self, body: &str) -> HandlerResult<()> {
169        let l = WriteLogRequest {
170            level: TRACE,
171            body: body.to_string(),
172        };
173        let _ = host_call(
174            &CURRENT_BINDING.read().unwrap(),
175            CAPID_LOGGING,
176            OP_LOG,
177            &serialize(l)?,
178        );
179        Ok(())
180    }
181}