iceoryx2_bb_log/logger/
buffer.rs

1// Copyright (c) 2023 Contributors to the Eclipse Foundation
2//
3// See the NOTICE file(s) distributed with this work for additional
4// information regarding copyright ownership.
5//
6// This program and the accompanying materials are made available under the
7// terms of the Apache Software License 2.0 which is available at
8// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
9// which is available at https://opensource.org/licenses/MIT.
10//
11// SPDX-License-Identifier: Apache-2.0 OR MIT
12
13use std::sync::Mutex;
14
15use crate::LogLevel;
16
17#[derive(Debug, Clone)]
18pub struct Entry {
19    pub log_level: LogLevel,
20    pub origin: String,
21    pub message: String,
22}
23
24pub struct Logger {
25    buffer: Mutex<Vec<Entry>>,
26}
27
28impl Default for Logger {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Logger {
35    pub const fn new() -> Logger {
36        Logger {
37            buffer: Mutex::new(vec![]),
38        }
39    }
40
41    pub fn len(&self) -> usize {
42        self.buffer
43            .lock()
44            .expect("Unable to acquire log buffer length since the lock of the log buffer failed.")
45            .len()
46    }
47
48    pub fn is_empty(&self) -> bool {
49        self.buffer
50            .lock()
51            .expect(
52                "Unable to acquire log buffer empty state since the lock of the log buffer failed.",
53            )
54            .is_empty()
55    }
56
57    pub fn contains(&self, log_level: LogLevel) -> bool {
58        let guard = self
59            .buffer
60            .lock()
61            .expect("Unable to check log buffer content since the lock of the log buffer failed.");
62
63        for entry in &*guard {
64            if entry.log_level == log_level {
65                return true;
66            }
67        }
68
69        false
70    }
71
72    pub fn clear(&self) {
73        self.buffer
74            .lock()
75            .expect("Unable to clear log buffer since the lock of the log buffer failed.")
76            .clear();
77    }
78
79    pub fn content(&self) -> Vec<Entry> {
80        self.buffer
81            .lock()
82            .expect("Unable to copy log buffer content since the lock of the log buffer failed.")
83            .clone()
84    }
85}
86
87impl crate::Log for Logger {
88    fn log(
89        &self,
90        log_level: LogLevel,
91        origin: core::fmt::Arguments,
92        formatted_message: core::fmt::Arguments,
93    ) {
94        self.buffer
95            .lock()
96            .expect("Unable to log message since the lock of the log buffer failed.")
97            .push(Entry {
98                log_level,
99                origin: origin.to_string(),
100                message: formatted_message.to_string(),
101            });
102    }
103}