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