fuchsia_triage/
inspect_logger.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#[cfg(target_os = "fuchsia")]
mod target {
    use fuchsia_inspect_contrib::inspect_log;
    use fuchsia_inspect_contrib::nodes::BoundedListNode;
    use std::sync::{LazyLock, Mutex};

    struct LogHolder {
        list: Mutex<Option<BoundedListNode>>,
    }

    impl LogHolder {
        fn new() -> Self {
            LogHolder { list: Mutex::new(None) }
        }
    }

    static LOGGER: LazyLock<LogHolder> = LazyLock::new(LogHolder::new);

    /// Provides a `BoundedListNode` to store logged warnings and errors in.
    pub fn set_log_list_node(node: BoundedListNode) {
        *LOGGER.list.lock().unwrap() = Some(node);
    }

    /// Logs a "warn" message to a list of messages in Inspect.
    /// Until set_log_list_node() is called, this will have no effect.
    pub(crate) fn log_warn(message: &str, namespace: &str, name: &str, error: &str) {
        log_problem("warn", message, namespace, name, error);
    }

    /// Logs an "Error" message to a list of messages in Inspect.
    /// Until set_log_list_node() is called, this will have no effect.
    pub(crate) fn log_error(message: &str, namespace: &str, name: &str, error: &str) {
        log_problem("error", message, namespace, name, error);
    }

    fn log_problem(level: &str, message: &str, namespace: &str, name: &str, error: &str) {
        let Some(ref mut list) = *LOGGER.list.lock().unwrap() else {
            return;
        };
        inspect_log!(
            list,
            level: level,
            message: message,
            namespace: namespace,
            name: name,
            error: error
        );
    }
}

#[cfg(target_os = "fuchsia")]
pub use target::*;

#[cfg(not(target_os = "fuchsia"))]
mod host {

    pub(crate) fn log_warn(_message: &str, _namespace: &str, _name: &str, _error: &str) {}

    pub(crate) fn log_error(_message: &str, _namespace: &str, _name: &str, _error: &str) {}
}

#[cfg(not(target_os = "fuchsia"))]
pub(crate) use host::*;