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"
//! `tracing_subscriber::Layer` that forwards `tracing` events to a [`LogClient`].

use std::fmt;
use std::sync::Arc;

use ::tracing::field::{Field, Visit};
use ::tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::LookupSpan;

use super::{AttrValue, Attributes, LogClient, LogEntry, LogInput, Severity};

/// Targets ignored by default so exporting logs never produces more logs (feedback loop).
const DEFAULT_IGNORED: &[&str] = &[
    "reqwest",
    "hyper",
    "hyper_util",
    "h2",
    "rustls",
    "tower",
    "tonic",
    "opentelemetry",
    "opentelemetry_sdk",
    "opentelemetry_otlp",
    "tokio",
];

/// Forwards `tracing` events to a [`LogClient`].
///
/// The `message` field becomes the body, other fields become attributes; `log.target`,
/// `code.filepath`, `code.lineno` and the current span name (`span.name`) are added. Events
/// from this crate and from the HTTP/OpenTelemetry stack are ignored by default.
///
/// ```no_run
/// # use std::sync::Arc;
/// # use grow_graylog::logging::{LogClient, LogLayer};
/// # fn demo(client: Arc<dyn LogClient>) {
/// use tracing_subscriber::prelude::*;
/// tracing_subscriber::registry().with(LogLayer::new(client)).init();
/// # }
/// ```
pub struct LogLayer {
    client: Arc<dyn LogClient>,
    min_severity: Severity,
    ignored: Vec<String>,
}

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

impl LogLayer {
    /// Layer forwarding `INFO` and above.
    pub fn new(client: Arc<dyn LogClient>) -> Self {
        let own = module_path!()
            .split("::")
            .next()
            .unwrap_or_default()
            .to_string();
        let mut ignored: Vec<String> = DEFAULT_IGNORED.iter().map(|s| s.to_string()).collect();
        ignored.push(own);
        LogLayer {
            client,
            min_severity: Severity::Info,
            ignored,
        }
    }

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

    /// Replaces the ignored target prefixes (module paths such as `hyper` or `my_app::noisy`).
    pub fn with_ignored_targets<S: Into<String>>(
        mut self,
        targets: impl IntoIterator<Item = S>,
    ) -> Self {
        self.ignored = targets.into_iter().map(Into::into).collect();
        self
    }

    fn is_ignored(&self, target: &str) -> bool {
        self.ignored.iter().any(|p| {
            target == p || (target.starts_with(p.as_str()) && target[p.len()..].starts_with("::"))
        })
    }
}

/// Maps a `tracing` level to a severity.
pub(crate) fn severity_of(level: &Level) -> Severity {
    match *level {
        Level::TRACE => Severity::Trace,
        Level::DEBUG => Severity::Debug,
        Level::INFO => Severity::Info,
        Level::WARN => Severity::Warn,
        _ => Severity::Error,
    }
}

#[derive(Default)]
struct FieldVisitor {
    message: Option<String>,
    attributes: Attributes,
}

impl FieldVisitor {
    fn put(&mut self, field: &Field, value: AttrValue) {
        if field.name() == "message" {
            self.message = Some(match value {
                AttrValue::String(s) => s,
                other => other.to_string(),
            });
        } else {
            self.attributes.insert(field.name().to_string(), value);
        }
    }
}

impl Visit for FieldVisitor {
    fn record_f64(&mut self, field: &Field, value: f64) {
        self.put(field, value.into());
    }
    fn record_i64(&mut self, field: &Field, value: i64) {
        self.put(field, value.into());
    }
    fn record_u64(&mut self, field: &Field, value: u64) {
        self.put(field, value.into());
    }
    fn record_bool(&mut self, field: &Field, value: bool) {
        self.put(field, value.into());
    }
    fn record_str(&mut self, field: &Field, value: &str) {
        self.put(field, value.into());
    }
    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
        self.put(field, value.to_string().into());
    }
    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.put(field, format!("{value:?}").into());
    }
}

impl<S> tracing_subscriber::Layer<S> for LogLayer
where
    S: Subscriber + for<'a> LookupSpan<'a>,
{
    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        let meta = event.metadata();
        let severity = severity_of(meta.level());
        if severity < self.min_severity || self.is_ignored(meta.target()) {
            return;
        }
        let mut visitor = FieldVisitor::default();
        event.record(&mut visitor);
        let mut attrs = visitor.attributes;
        attrs.insert("log.target".into(), meta.target().into());
        if let Some(file) = meta.file() {
            attrs.insert("code.filepath".into(), file.into());
        }
        if let Some(line) = meta.line() {
            attrs.insert("code.lineno".into(), line.into());
        }
        if let Some(span) = ctx.event_span(event) {
            attrs.insert("span.name".into(), span.name().into());
        }
        let input = LogInput::new(visitor.message.unwrap_or_default())
            .severity(severity)
            .attributes(attrs);
        self.client.send(LogEntry::Input(input));
    }
}