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 fuchsia_sync::Mutex;
10    use std::sync::LazyLock;
11
12    struct LogHolder {
13        list: Mutex<Option<BoundedListNode>>,
14    }
15
16    impl LogHolder {
17        fn new() -> Self {
18            LogHolder { list: Mutex::new(None) }
19        }
20    }
21
22    static LOGGER: LazyLock<LogHolder> = LazyLock::new(LogHolder::new);
23
24    /// Provides a `BoundedListNode` to store logged warnings and errors in.
25    pub fn set_log_list_node(node: BoundedListNode) {
26        *LOGGER.list.lock() = Some(node);
27    }
28
29    /// Logs a "warn" message to a list of messages in Inspect.
30    /// Until set_log_list_node() is called, this will have no effect.
31    pub(crate) fn log_warn(message: &str, namespace: &str, name: &str, error: &str) {
32        log_problem("warn", message, namespace, name, error);
33    }
34
35    /// Logs an "Error" message to a list of messages in Inspect.
36    /// Until set_log_list_node() is called, this will have no effect.
37    pub(crate) fn log_error(message: &str, namespace: &str, name: &str, error: &str) {
38        log_problem("error", message, namespace, name, error);
39    }
40
41    fn log_problem(level: &str, message: &str, namespace: &str, name: &str, error: &str) {
42        let Some(ref mut list) = *LOGGER.list.lock() else {
43            return;
44        };
45        inspect_log!(
46            list,
47            level: level,
48            message: message,
49            namespace: namespace,
50            name: name,
51            error: error
52        );
53    }
54}
55
56#[cfg(target_os = "fuchsia")]
57pub use target::*;
58
59#[cfg(not(target_os = "fuchsia"))]
60mod host {
61
62    pub(crate) fn log_warn(_message: &str, _namespace: &str, _name: &str, _error: &str) {}
63
64    pub(crate) fn log_error(_message: &str, _namespace: &str, _name: &str, _error: &str) {}
65}
66
67#[cfg(not(target_os = "fuchsia"))]
68pub(crate) use host::*;