fuchsia_triage/
inspect_logger.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#[cfg(target_os = "fuchsia")]
6mod target {
7    use fuchsia_inspect_contrib::inspect_log;
8    use fuchsia_inspect_contrib::nodes::BoundedListNode;
9    use std::sync::{LazyLock, Mutex};
10
11    struct LogHolder {
12        list: Mutex<Option<BoundedListNode>>,
13    }
14
15    impl LogHolder {
16        fn new() -> Self {
17            LogHolder { list: Mutex::new(None) }
18        }
19    }
20
21    static LOGGER: LazyLock<LogHolder> = LazyLock::new(LogHolder::new);
22
23    /// Provides a `BoundedListNode` to store logged warnings and errors in.
24    pub fn set_log_list_node(node: BoundedListNode) {
25        *LOGGER.list.lock().unwrap() = Some(node);
26    }
27
28    /// Logs a "warn" message to a list of messages in Inspect.
29    /// Until set_log_list_node() is called, this will have no effect.
30    pub(crate) fn log_warn(message: &str, namespace: &str, name: &str, error: &str) {
31        log_problem("warn", message, namespace, name, error);
32    }
33
34    /// Logs an "Error" message to a list of messages in Inspect.
35    /// Until set_log_list_node() is called, this will have no effect.
36    pub(crate) fn log_error(message: &str, namespace: &str, name: &str, error: &str) {
37        log_problem("error", message, namespace, name, error);
38    }
39
40    fn log_problem(level: &str, message: &str, namespace: &str, name: &str, error: &str) {
41        let Some(ref mut list) = *LOGGER.list.lock().unwrap() else {
42            return;
43        };
44        inspect_log!(
45            list,
46            level: level,
47            message: message,
48            namespace: namespace,
49            name: name,
50            error: error
51        );
52    }
53}
54
55#[cfg(target_os = "fuchsia")]
56pub use target::*;
57
58#[cfg(not(target_os = "fuchsia"))]
59mod host {
60
61    pub(crate) fn log_warn(_message: &str, _namespace: &str, _name: &str, _error: &str) {}
62
63    pub(crate) fn log_error(_message: &str, _namespace: &str, _name: &str, _error: &str) {}
64}
65
66#[cfg(not(target_os = "fuchsia"))]
67pub(crate) use host::*;