canic/ops/model/memory/
log.rs

1use crate::{
2    Error,
3    log::Level,
4    model::memory::log::{LogEntry, StableLog},
5};
6use candid::CandidType;
7use serde::Serialize;
8
9///
10/// LogEntryDto
11///
12
13#[derive(CandidType, Clone, Debug, Serialize)]
14pub struct LogEntryDto {
15    pub index: u64,
16    pub created_at: u64,
17    pub crate_name: String,
18    pub level: Level,
19    pub topic: Option<String>,
20    pub message: String,
21}
22
23impl LogEntryDto {
24    fn from_pair(index: usize, entry: LogEntry) -> Self {
25        Self {
26            index: index as u64,
27            created_at: entry.created_at,
28            crate_name: entry.crate_name,
29            level: entry.level,
30            topic: entry.topic,
31            message: entry.message,
32        }
33    }
34}
35
36///
37/// LogPageDto
38///
39
40#[derive(CandidType, Serialize)]
41pub struct LogPageDto {
42    pub entries: Vec<LogEntryDto>,
43    pub total: u64,
44}
45
46///
47/// LogOps
48///
49
50pub struct LogOps;
51
52impl LogOps {
53    /// Append a log entry to stable storage.
54    pub fn append<T: ToString, M: AsRef<str>>(
55        crate_name: &str,
56        topic: Option<T>,
57        level: Level,
58        message: M,
59    ) -> Result<u64, Error> {
60        StableLog::append(crate_name, topic, level, message)
61    }
62
63    ///
64    /// Export a page of log entries and the total count.
65    ///
66    #[must_use]
67    pub fn page(
68        crate_name: Option<String>,
69        topic: Option<String>,
70        min_level: Option<Level>,
71        offset: u64,
72        limit: u64,
73    ) -> LogPageDto {
74        let (raw_entries, total) = StableLog::entries_page_filtered(
75            crate_name.as_deref(),
76            topic.as_deref(),
77            min_level,
78            offset,
79            limit,
80        );
81
82        let entries = raw_entries
83            .into_iter()
84            .map(|(i, entry)| LogEntryDto::from_pair(i, entry))
85            .collect();
86
87        LogPageDto { entries, total }
88    }
89}