Skip to main content

flaron_sdk/
logging.rs

1//! Structured logging from inside a flare.
2//!
3//! Messages are forwarded to the edge node's `slog` stream tagged with the
4//! flare name and domain. The host enforces a per-invocation cap of 100 log
5//! lines and truncates each message to 4 KiB.
6
7use crate::{ffi, mem};
8
9/// Log an informational message.
10pub fn info(msg: &str) {
11    let (ptr, len) = mem::host_arg_str(msg);
12    unsafe { ffi::log_info(ptr, len) }
13}
14
15/// Log a warning.
16pub fn warn(msg: &str) {
17    let (ptr, len) = mem::host_arg_str(msg);
18    unsafe { ffi::log_warn(ptr, len) }
19}
20
21/// Log an error.
22pub fn error(msg: &str) {
23    let (ptr, len) = mem::host_arg_str(msg);
24    unsafe { ffi::log_error(ptr, len) }
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use crate::ffi::test_host;
31
32    #[test]
33    fn info_records_message_at_info_level() {
34        test_host::reset();
35        info("hello world");
36        let logs = test_host::read_mock(|m| m.logs.clone());
37        assert_eq!(logs, vec![("info", "hello world".into())]);
38    }
39
40    #[test]
41    fn warn_records_message_at_warn_level() {
42        test_host::reset();
43        warn("careful");
44        let logs = test_host::read_mock(|m| m.logs.clone());
45        assert_eq!(logs, vec![("warn", "careful".into())]);
46    }
47
48    #[test]
49    fn error_records_message_at_error_level() {
50        test_host::reset();
51        error("oh no");
52        let logs = test_host::read_mock(|m| m.logs.clone());
53        assert_eq!(logs, vec![("error", "oh no".into())]);
54    }
55
56    #[test]
57    fn multiple_logs_preserve_order() {
58        test_host::reset();
59        info("1");
60        warn("2");
61        error("3");
62        info("4");
63        let logs = test_host::read_mock(|m| m.logs.clone());
64        assert_eq!(
65            logs,
66            vec![
67                ("info", "1".into()),
68                ("warn", "2".into()),
69                ("error", "3".into()),
70                ("info", "4".into()),
71            ]
72        );
73    }
74}