Skip to content

Commit

Permalink
feat: renders kvs in OpentelemetryLog (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
andylokandy authored Aug 9, 2024
1 parent 4814ad8 commit e2b7b10
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/append/opentelemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ use std::time::SystemTime;

use log::Record;
use opentelemetry::logs::AnyValue;
use opentelemetry::logs::LogRecord as _;
use opentelemetry::logs::Logger;
use opentelemetry::logs::LoggerProvider as ILoggerProvider;
use opentelemetry::logs::Severity;
use opentelemetry::InstrumentationLibrary;
use opentelemetry_otlp::Protocol;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::logs::LogRecord;
use opentelemetry_sdk::logs::LoggerProvider;

use crate::append::Append;
Expand Down Expand Up @@ -111,8 +113,40 @@ impl Append for OpentelemetryLog {
record.observed_timestamp = Some(SystemTime::now());
record.severity_number = Some(log_level_to_otel_severity(log_record.level()));
record.severity_text = Some(log_record.level().as_str().into());
record.target = Some(log_record.target().to_string().into());
record.body = Some(AnyValue::from(log_record.args().to_string()));

if let Some(module_path) = log_record.module_path() {
record.add_attribute("module_path", module_path.to_string());
}
if let Some(file) = log_record.file() {
record.add_attribute("file", file.to_string());
}
if let Some(line) = log_record.line() {
record.add_attribute("line", line);
}

struct KvExtractor<'a> {
record: &'a mut LogRecord,
}

impl<'a, 'kvs> log::kv::Visitor<'kvs> for KvExtractor<'a> {
fn visit_pair(
&mut self,
key: log::kv::Key<'kvs>,
value: log::kv::Value<'kvs>,
) -> Result<(), log::kv::Error> {
self.record
.add_attribute(key.to_string(), value.to_string());
Ok(())
}
}

let mut extractor = KvExtractor {
record: &mut record,
};
log_record.key_values().visit(&mut extractor).ok();

logger.emit(record);
Ok(())
}
Expand Down

0 comments on commit e2b7b10

Please sign in to comment.