Skip to content

Commit 88cae2c

Browse files
authored
test: Add test to show how to add baggage to logrecords via processor (#2738)
1 parent f15a337 commit 88cae2c

File tree

2 files changed

+78
-14
lines changed

2 files changed

+78
-14
lines changed

opentelemetry-sdk/src/logs/mod.rs

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@ pub mod log_processor_with_async_runtime;
3535
mod tests {
3636
use super::*;
3737
use crate::Resource;
38+
use opentelemetry::baggage::BaggageExt;
3839
use opentelemetry::logs::LogRecord;
3940
use opentelemetry::logs::{Logger, LoggerProvider, Severity};
40-
use opentelemetry::InstrumentationScope;
4141
use opentelemetry::{logs::AnyValue, Key, KeyValue};
42+
use opentelemetry::{Context, InstrumentationScope};
4243
use std::borrow::Borrow;
4344
use std::collections::HashMap;
4445

@@ -150,4 +151,63 @@ mod tests {
150151
.attributes()
151152
.eq(&[KeyValue::new("test_k", "test_v")]));
152153
}
154+
155+
#[derive(Debug)]
156+
struct EnrichWithBaggageProcessor;
157+
impl LogProcessor for EnrichWithBaggageProcessor {
158+
fn emit(&self, data: &mut SdkLogRecord, _instrumentation: &InstrumentationScope) {
159+
Context::map_current(|cx| {
160+
for (kk, vv) in cx.baggage().iter() {
161+
data.add_attribute(kk.clone(), vv.0.clone());
162+
}
163+
});
164+
}
165+
166+
fn force_flush(&self) -> crate::error::OTelSdkResult {
167+
Ok(())
168+
}
169+
170+
fn shutdown(&self) -> crate::error::OTelSdkResult {
171+
Ok(())
172+
}
173+
}
174+
#[test]
175+
fn log_and_baggage() {
176+
// Arrange
177+
let exporter: InMemoryLogExporter = InMemoryLogExporter::default();
178+
let logger_provider = SdkLoggerProvider::builder()
179+
.with_log_processor(EnrichWithBaggageProcessor)
180+
.with_log_processor(SimpleLogProcessor::new(exporter.clone()))
181+
.build();
182+
183+
// Act
184+
let logger = logger_provider.logger("test-logger");
185+
let context_with_baggage =
186+
Context::current_with_baggage(vec![KeyValue::new("key-from-bag", "value-from-bag")]);
187+
let _cx_guard = context_with_baggage.attach();
188+
let mut log_record = logger.create_log_record();
189+
log_record.add_attribute("key", "value");
190+
logger.emit(log_record);
191+
192+
// Assert
193+
let exported_logs = exporter
194+
.get_emitted_logs()
195+
.expect("Logs are expected to be exported.");
196+
assert_eq!(exported_logs.len(), 1);
197+
let log = exported_logs
198+
.first()
199+
.expect("Atleast one log is expected to be present.");
200+
assert_eq!(log.instrumentation.name(), "test-logger");
201+
assert_eq!(log.record.attributes_len(), 2);
202+
203+
// Assert that the log record contains the baggage attribute
204+
// and the attribute added to the log record.
205+
assert!(log
206+
.record
207+
.attributes_contains(&Key::new("key"), &AnyValue::String("value".into())));
208+
assert!(log.record.attributes_contains(
209+
&Key::new("key-from-bag"),
210+
&AnyValue::String("value-from-bag".into())
211+
));
212+
}
153213
}

opentelemetry/src/baggage.rs

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@
1313
//! Baggage can be sent between systems using a baggage propagator in
1414
//! accordance with the [W3C Baggage] specification.
1515
//!
16+
//! Note: Baggage is not automatically added to any telemetry. Users have to
17+
//! explicitly add baggage entries to telemetry items.
18+
//!
19+
//!
1620
//! [W3C Baggage]: https://w3c.github.io/baggage
1721
use crate::{Context, Key, KeyValue, StringValue};
1822
use std::collections::hash_map::Entry;
@@ -75,10 +79,10 @@ impl Baggage {
7579
/// ```
7680
/// use opentelemetry::{baggage::Baggage, StringValue};
7781
///
78-
/// let mut cc = Baggage::new();
79-
/// let _ = cc.insert("my-name", "my-value");
82+
/// let mut baggage = Baggage::new();
83+
/// let _ = baggage.insert("my-name", "my-value");
8084
///
81-
/// assert_eq!(cc.get("my-name"), Some(&StringValue::from("my-value")))
85+
/// assert_eq!(baggage.get("my-name"), Some(&StringValue::from("my-value")))
8286
/// ```
8387
pub fn get<K: AsRef<str>>(&self, key: K) -> Option<&StringValue> {
8488
self.inner.get(key.as_ref()).map(|(value, _metadata)| value)
@@ -90,11 +94,11 @@ impl Baggage {
9094
/// ```
9195
/// use opentelemetry::{baggage::{Baggage, BaggageMetadata}, StringValue};
9296
///
93-
/// let mut cc = Baggage::new();
94-
/// let _ = cc.insert("my-name", "my-value");
97+
/// let mut baggage = Baggage::new();
98+
/// let _ = baggage.insert("my-name", "my-value");
9599
///
96100
/// // By default, the metadata is empty
97-
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(StringValue::from("my-value"), BaggageMetadata::from(""))))
101+
/// assert_eq!(baggage.get_with_metadata("my-name"), Some(&(StringValue::from("my-value"), BaggageMetadata::from(""))))
98102
/// ```
99103
pub fn get_with_metadata<K: AsRef<str>>(
100104
&self,
@@ -113,10 +117,10 @@ impl Baggage {
113117
/// ```
114118
/// use opentelemetry::{baggage::Baggage, StringValue};
115119
///
116-
/// let mut cc = Baggage::new();
117-
/// let _ = cc.insert("my-name", "my-value");
120+
/// let mut baggage = Baggage::new();
121+
/// let _ = baggage.insert("my-name", "my-value");
118122
///
119-
/// assert_eq!(cc.get("my-name"), Some(&StringValue::from("my-value")))
123+
/// assert_eq!(baggage.get("my-name"), Some(&StringValue::from("my-value")))
120124
/// ```
121125
pub fn insert<K, V>(&mut self, key: K, value: V) -> Option<StringValue>
122126
where
@@ -127,7 +131,7 @@ impl Baggage {
127131
.map(|pair| pair.0)
128132
}
129133

130-
/// Inserts a name/value pair into the baggage.
134+
/// Inserts a name/value(+metadata) pair into the baggage.
131135
///
132136
/// Same with `insert`, if the name was not present, [`None`] will be returned.
133137
/// If the name is present, the old value and metadata will be returned.
@@ -139,10 +143,10 @@ impl Baggage {
139143
/// ```
140144
/// use opentelemetry::{baggage::{Baggage, BaggageMetadata}, StringValue};
141145
///
142-
/// let mut cc = Baggage::new();
143-
/// let _ = cc.insert_with_metadata("my-name", "my-value", "test");
146+
/// let mut baggage = Baggage::new();
147+
/// let _ = baggage.insert_with_metadata("my-name", "my-value", "test");
144148
///
145-
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(StringValue::from("my-value"), BaggageMetadata::from("test"))))
149+
/// assert_eq!(baggage.get_with_metadata("my-name"), Some(&(StringValue::from("my-value"), BaggageMetadata::from("test"))))
146150
/// ```
147151
pub fn insert_with_metadata<K, V, S>(
148152
&mut self,

0 commit comments

Comments
 (0)