tembra_runtime/host/log.rs
1//! Diagnostic records of native Orbs, for the host's log observer.
2
3use super::*;
4
5/// A diagnostic record, attributed by the host to the Orb that wrote it, never by a name the Orb
6/// gives.
7#[derive(Clone, Debug, Serialize)]
8pub struct LogRecord {
9 pub orb: String,
10 pub level: String,
11 pub message: String,
12}
13
14impl Host {
15 /// Observe the records native Orbs write with [`Context::log`]; a later observer replaces this
16 /// one. Without an observer, records are dropped. The host releases its observer when it
17 /// closes.
18 pub fn on_log(&self, observer: impl Fn(&LogRecord) + 'static) {
19 *self.0.log_observer.borrow_mut() = Some(Rc::new(observer));
20 }
21}
22
23impl Context {
24 /// Hand a record to the host's log observer, attributed to the Orb running this invocation,
25 /// or, in a resource's opener or closer, to the Orb owning the resource; without an observer
26 /// it is dropped. Writing needs no admission: a cancelled call still logs. An observer that
27 /// panics does not interrupt the call.
28 pub fn log(&self, level: impl Into<String>, message: impl Into<String>) -> Result<()> {
29 let orb = self.attributed()?;
30 let observer = self.host.0.log_observer.borrow().clone();
31 let Some(observer) = observer else {
32 return Ok(());
33 };
34 let record = LogRecord {
35 orb,
36 level: level.into(),
37 message: message.into(),
38 };
39 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observer(&record)));
40 Ok(())
41 }
42}