grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! [`LogClient`], its batching implementation and the [`Logger`] facade.

use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use async_trait::async_trait;

use super::{
    active_trace_context, AttrValue, Attributes, BatchOptions, BatchProcessor, BatchStats,
    LogExporter, LogInput, LogRecord, RedactionProcessor, Severity,
};
use crate::core::Result;

/// Something a [`LogClient`] can send: a complete record or an input to fill in.
#[derive(Debug, Clone, PartialEq)]
pub enum LogEntry {
    /// A complete record (only `resource` defaults and redaction are applied).
    Record(LogRecord),
    /// An input; timestamp, severity, resource and trace context are filled in.
    Input(LogInput),
}

impl From<LogRecord> for LogEntry {
    fn from(r: LogRecord) -> Self {
        LogEntry::Record(r)
    }
}

impl From<LogInput> for LogEntry {
    fn from(i: LogInput) -> Self {
        LogEntry::Input(i)
    }
}

impl From<&str> for LogEntry {
    fn from(message: &str) -> Self {
        LogEntry::Input(LogInput::new(message))
    }
}

impl From<String> for LogEntry {
    fn from(message: String) -> Self {
        LogEntry::Input(LogInput::new(message))
    }
}

/// Client that ships logs to a service (SPEC §4 `LogClient`).
#[async_trait]
pub trait LogClient: Send + Sync {
    /// Enqueues one record (applies redaction and defaults). Never blocks unless the batch
    /// drop policy is `Block`.
    fn send(&self, entry: LogEntry);
    /// Enqueues several records.
    fn send_batch(&self, entries: Vec<LogEntry>) {
        for e in entries {
            self.send(e);
        }
    }
    /// Exports everything queued now.
    async fn flush(&self, timeout: Option<Duration>) -> Result<()>;
    /// Flushes and shuts down; idempotent.
    async fn close(&self) -> Result<()>;
    /// Batch counters.
    fn stats(&self) -> BatchStats;
    /// A [`Logger`] facade writing to this client; `name` becomes the `logger.name` attribute.
    fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger;
}

struct Inner {
    processor: BatchProcessor,
    resource: Attributes,
    redaction: Option<RedactionProcessor>,
    min_severity: Severity,
    closed: AtomicBool,
}

/// [`LogClient`] built from a [`LogExporter`], [`BatchOptions`], resource and redaction.
/// Cheap to clone; clones share the queue.
#[derive(Clone)]
pub struct BatchingLogClient {
    inner: Arc<Inner>,
}

impl fmt::Debug for BatchingLogClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BatchingLogClient")
            .field("resource", &self.inner.resource)
            .field("stats", &self.stats())
            .finish()
    }
}

/// Builder for [`BatchingLogClient`].
pub struct BatchingLogClientBuilder {
    exporter: Arc<dyn LogExporter>,
    batch: BatchOptions,
    resource: Attributes,
    redaction: Option<RedactionProcessor>,
    min_severity: Severity,
}

impl BatchingLogClientBuilder {
    /// Batch options (default [`BatchOptions::default`]).
    pub fn batch_options(mut self, opts: BatchOptions) -> Self {
        self.batch = opts;
        self
    }

    /// Replaces the resource attributes added to every record.
    pub fn resource(mut self, resource: Attributes) -> Self {
        self.resource = resource;
        self
    }

    /// Adds one resource attribute.
    pub fn resource_attribute(
        mut self,
        key: impl Into<String>,
        value: impl Into<AttrValue>,
    ) -> Self {
        self.resource.insert(key.into(), value.into());
        self
    }

    /// Redaction applied to every record (default [`RedactionProcessor::default`]); `None`
    /// disables redaction.
    pub fn redaction(mut self, redaction: Option<RedactionProcessor>) -> Self {
        self.redaction = redaction;
        self
    }

    /// Default minimum severity for loggers from [`LogClient::logger`] (default `Info`).
    pub fn min_severity(mut self, severity: Severity) -> Self {
        self.min_severity = severity;
        self
    }

    /// Starts the client; must be called inside a tokio runtime.
    pub fn build(self) -> Result<BatchingLogClient> {
        let processor = BatchProcessor::new(self.exporter, self.batch)?;
        Ok(BatchingLogClient {
            inner: Arc::new(Inner {
                processor,
                resource: self.resource,
                redaction: self.redaction,
                min_severity: self.min_severity,
                closed: AtomicBool::new(false),
            }),
        })
    }
}

impl BatchingLogClient {
    /// Starts building a client around `exporter`.
    pub fn builder(exporter: Arc<dyn LogExporter>) -> BatchingLogClientBuilder {
        BatchingLogClientBuilder {
            exporter,
            batch: BatchOptions::default(),
            resource: Attributes::new(),
            redaction: Some(RedactionProcessor::default()),
            min_severity: Severity::Info,
        }
    }

    /// Client with default options.
    pub fn new(exporter: Arc<dyn LogExporter>) -> Result<Self> {
        Self::builder(exporter).build()
    }

    /// The underlying processor.
    pub fn processor(&self) -> &BatchProcessor {
        &self.inner.processor
    }

    /// Applies defaults, trace correlation and redaction, producing the record that is queued.
    pub fn prepare(&self, entry: LogEntry) -> LogRecord {
        let mut record = match entry {
            LogEntry::Record(r) => r,
            LogEntry::Input(i) => {
                let severity = i.severity.unwrap_or_default();
                let mut r = LogRecord {
                    timestamp: i.timestamp.unwrap_or_else(SystemTime::now),
                    observed_timestamp: Some(SystemTime::now()),
                    severity,
                    severity_text: severity.text().to_string(),
                    body: i.message,
                    attributes: i.attributes,
                    resource: Attributes::new(),
                    trace_id: i.trace_id,
                    span_id: i.span_id,
                    trace_flags: None,
                };
                if r.trace_id.is_none() {
                    if let Some((trace, span, flags)) = active_trace_context() {
                        r.trace_id = Some(trace);
                        r.span_id = Some(span);
                        r.trace_flags = Some(flags);
                    }
                }
                r
            }
        };
        for (k, v) in &self.inner.resource {
            record
                .resource
                .entry(k.clone())
                .or_insert_with(|| v.clone());
        }
        if let Some(redaction) = &self.inner.redaction {
            redaction.apply(&mut record);
        }
        record
    }

    /// Sends and waits for room under the `Block` policy instead of blocking the thread.
    pub async fn send_async(&self, entry: LogEntry) -> bool {
        let record = self.prepare(entry);
        self.inner.processor.add_async(record).await
    }
}

#[async_trait]
impl LogClient for BatchingLogClient {
    fn send(&self, entry: LogEntry) {
        let record = self.prepare(entry);
        self.inner.processor.add(record);
    }

    async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
        self.inner.processor.flush(timeout).await
    }

    async fn close(&self) -> Result<()> {
        if self.inner.closed.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        self.inner.processor.shutdown(None).await
    }

    fn stats(&self) -> BatchStats {
        self.inner.processor.stats()
    }

    fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger {
        let mut logger = Logger::new(Arc::new(self.clone()), attributes)
            .with_min_severity(self.inner.min_severity);
        if let Some(name) = name {
            logger.attributes.insert("logger.name".into(), name.into());
        }
        logger
    }
}

/// Leveled logging facade over a [`LogClient`] (SPEC §4 `Logger`).
///
/// Records below the minimum severity (default `Info`) are discarded. When an OpenTelemetry
/// span is active, its trace id, span id and flags are attached.
#[derive(Clone)]
pub struct Logger {
    client: Arc<dyn LogClient>,
    attributes: Attributes,
    min_severity: Severity,
}

impl fmt::Debug for Logger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Logger")
            .field("attributes", &self.attributes)
            .field("min_severity", &self.min_severity)
            .finish()
    }
}

impl Logger {
    /// Logger writing to `client` with base attributes.
    pub fn new(client: Arc<dyn LogClient>, attributes: Attributes) -> Self {
        Logger {
            client,
            attributes,
            min_severity: Severity::Info,
        }
    }

    /// Changes the minimum severity.
    pub fn with_min_severity(mut self, severity: Severity) -> Self {
        self.min_severity = severity;
        self
    }

    /// Minimum severity in use.
    pub fn min_severity(&self) -> Severity {
        self.min_severity
    }

    /// Base attributes.
    pub fn attributes(&self) -> &Attributes {
        &self.attributes
    }

    /// Whether `severity` would be logged.
    pub fn enabled(&self, severity: Severity) -> bool {
        severity >= self.min_severity
    }

    /// A logger with extra base attributes (child attributes win).
    pub fn child(&self, attributes: Attributes) -> Logger {
        let mut merged = self.attributes.clone();
        merged.extend(attributes);
        Logger {
            client: Arc::clone(&self.client),
            attributes: merged,
            min_severity: self.min_severity,
        }
    }

    /// Logs at `severity`; call attributes override base attributes.
    pub fn log(&self, severity: Severity, message: impl Into<String>, attributes: Attributes) {
        if !self.enabled(severity) {
            return;
        }
        let mut attrs = self.attributes.clone();
        attrs.extend(attributes);
        let input = LogInput::new(message).severity(severity).attributes(attrs);
        self.client.send(LogEntry::Input(input));
    }

    /// Logs at `TRACE`.
    pub fn trace(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Trace, message, attributes);
    }
    /// Logs at `DEBUG`.
    pub fn debug(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Debug, message, attributes);
    }
    /// Logs at `INFO`.
    pub fn info(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Info, message, attributes);
    }
    /// Logs at `WARN`.
    pub fn warn(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Warn, message, attributes);
    }
    /// Logs at `ERROR`.
    pub fn error(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Error, message, attributes);
    }
    /// Logs at `FATAL`.
    pub fn fatal(&self, message: impl Into<String>, attributes: Attributes) {
        self.log(Severity::Fatal, message, attributes);
    }
}