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};
const DEFAULT_IGNORED: &[&str] = &[
"reqwest",
"hyper",
"hyper_util",
"h2",
"rustls",
"tower",
"tonic",
"opentelemetry",
"opentelemetry_sdk",
"opentelemetry_otlp",
"tokio",
];
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 {
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,
}
}
pub fn with_min_severity(mut self, severity: Severity) -> Self {
self.min_severity = severity;
self
}
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("::"))
})
}
}
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));
}
}