cm_logger/
scoped.rs

1// Copyright 2021 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
5use diagnostics_log::{PublishError, Publisher, PublisherOptions};
6use fidl::endpoints::ClientEnd;
7use fidl_fuchsia_logger as flogger;
8use thiserror::Error;
9
10#[derive(Debug, Error)]
11pub enum ScopedLoggerError {
12    #[error("could not create publisher")]
13    PublishError(#[source] PublishError),
14}
15
16#[derive(Clone)]
17pub struct ScopedLogger {
18    publisher: Publisher,
19}
20
21impl ScopedLogger {
22    pub fn create(logsink: ClientEnd<flogger::LogSinkMarker>) -> Result<Self, ScopedLoggerError> {
23        let publisher = Publisher::new(
24            PublisherOptions::default().wait_for_initial_interest(false).use_log_sink(logsink),
25        )
26        .map_err(ScopedLoggerError::PublishError)?;
27        Ok(Self { publisher })
28    }
29}
30
31impl log::Log for ScopedLogger {
32    #[inline]
33    fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
34        self.publisher.enabled(metadata)
35    }
36
37    #[inline]
38    fn log(&self, record: &log::Record<'_>) {
39        self.publisher.log(record);
40    }
41
42    #[inline]
43    fn flush(&self) {
44        self.publisher.flush();
45    }
46}