Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: renders kvs in OpentelemetryLog #31

Merged
merged 2 commits into from
Aug 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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