Skip to content

Commit

Permalink
Merge branch 'main' into global-error-handler-cleanup-logs-sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
cijothomas authored Oct 14, 2024
2 parents e99195b + 3f5c230 commit a566aac
Show file tree
Hide file tree
Showing 19 changed files with 175 additions and 175 deletions.
2 changes: 1 addition & 1 deletion examples/metrics-advanced/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ publish = false
[dependencies]
opentelemetry = { path = "../../opentelemetry", features = ["metrics"] }
opentelemetry_sdk = { path = "../../opentelemetry-sdk", features = ["metrics", "rt-tokio"] }
opentelemetry-stdout = { path = "../../opentelemetry-stdout", features = ["metrics"]}
opentelemetry-stdout = { path = "../../opentelemetry-stdout", features = ["metrics"] }
tokio = { workspace = true, features = ["full"] }
serde_json = { workspace = true }
7 changes: 6 additions & 1 deletion examples/metrics-advanced/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use opentelemetry::global;
use opentelemetry::Key;
use opentelemetry::KeyValue;
use opentelemetry_sdk::metrics::reader::DeltaTemporalitySelector;
use opentelemetry_sdk::metrics::{
Aggregation, Instrument, PeriodicReader, SdkMeterProvider, Stream,
};
Expand Down Expand Up @@ -44,7 +45,11 @@ fn init_meter_provider() -> opentelemetry_sdk::metrics::SdkMeterProvider {
}
};

let exporter = opentelemetry_stdout::MetricsExporterBuilder::default().build();
// Build exporter using Delta Temporality.
let exporter = opentelemetry_stdout::MetricsExporterBuilder::default()
.with_temporality_selector(DeltaTemporalitySelector::new())
.build();

let reader = PeriodicReader::builder(exporter, runtime::Tokio).build();
let provider = SdkMeterProvider::builder()
.with_reader(reader)
Expand Down
1 change: 1 addition & 0 deletions opentelemetry-appender-log/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## vNext

- Bump MSRV to 1.70 [#2179](https://github.com/open-telemetry/opentelemetry-rust/pull/2179)
- [2193](https://github.com/open-telemetry/opentelemetry-rust/pull/2193) `opentelemetry-appender-log`: Output experimental code attributes

## v0.26.0
Released 2024-Sep-30
Expand Down
17 changes: 13 additions & 4 deletions opentelemetry-appender-log/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,26 @@ rust-version = "1.70"
edition = "2021"

[dependencies]
opentelemetry = { version = "0.26", path = "../opentelemetry", features = ["logs"]}
log = { workspace = true, features = ["kv", "std"]}
opentelemetry = { version = "0.26", path = "../opentelemetry", features = [
"logs",
] }
log = { workspace = true, features = ["kv", "std"] }
serde = { workspace = true, optional = true, features = ["std"] }
opentelemetry-semantic-conventions = { path = "../opentelemetry-semantic-conventions", optional = true, features = [
"semconv_experimental",
] }

[features]
logs_level_enabled = ["opentelemetry/logs_level_enabled"]
with-serde = ["log/kv_serde", "serde"]
experimental_metadata_attributes = ["dep:opentelemetry-semantic-conventions"]

[dev-dependencies]
opentelemetry_sdk = { path = "../opentelemetry-sdk", features = [ "testing", "logs_level_enabled" ] }
opentelemetry-stdout = { path = "../opentelemetry-stdout", features = ["logs"]}
opentelemetry_sdk = { path = "../opentelemetry-sdk", features = [
"testing",
"logs_level_enabled",
] }
opentelemetry-stdout = { path = "../opentelemetry-stdout", features = ["logs"] }
log = { workspace = true, features = ["kv_serde"] }
tokio = { workspace = true }
serde = { workspace = true, features = ["std", "derive"] }
72 changes: 72 additions & 0 deletions opentelemetry-appender-log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ use opentelemetry::{
logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity},
Key,
};
#[cfg(feature = "experimental_metadata_attributes")]
use opentelemetry_semantic_conventions::attribute::{CODE_FILEPATH, CODE_LINENO, CODE_NAMESPACE};
use std::borrow::Cow;

pub struct OpenTelemetryLogBridge<P, L>
Expand Down Expand Up @@ -130,6 +132,28 @@ where
log_record.set_severity_number(severity_of_level(record.level()));
log_record.set_severity_text(record.level().as_str());
log_record.set_body(AnyValue::from(record.args().to_string()));

#[cfg(feature = "experimental_metadata_attributes")]
{
if let Some(filepath) = record.file() {
log_record.add_attribute(
Key::new(CODE_FILEPATH),
AnyValue::from(filepath.to_string()),
);
}

if let Some(line_no) = record.line() {
log_record.add_attribute(Key::new(CODE_LINENO), AnyValue::from(line_no));
}

if let Some(module) = record.module_path() {
log_record.add_attribute(
Key::new(CODE_NAMESPACE),
AnyValue::from(module.to_string()),
);
}
}

log_record.add_attributes(log_attributes(record.key_values()));
log_record.set_target(record.metadata().target().to_string());

Expand Down Expand Up @@ -1127,6 +1151,54 @@ mod tests {
}
}

#[cfg(feature = "experimental_metadata_attributes")]
#[test]
fn logbridge_code_attributes() {
use opentelemetry_semantic_conventions::attribute::{
CODE_FILEPATH, CODE_LINENO, CODE_NAMESPACE,
};

let exporter = InMemoryLogsExporter::default();

let logger_provider = LoggerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();

let otel_log_appender = OpenTelemetryLogBridge::new(&logger_provider);

otel_log_appender.log(
&log::RecordBuilder::new()
.level(log::Level::Warn)
.args(format_args!("WARN"))
.file(Some("src/main.rs"))
.module_path(Some("service"))
.line(Some(101))
.build(),
);

let logs = exporter.get_emitted_logs().unwrap();

let get = |needle: &str| -> Option<AnyValue> {
logs[0].record.attributes_iter().find_map(|(k, v)| {
if k.as_str() == needle {
Some(v.clone())
} else {
None
}
})
};

assert_eq!(
Some(AnyValue::String(StringValue::from("src/main.rs"))),
get(CODE_FILEPATH)
);
assert_eq!(
Some(AnyValue::String(StringValue::from("service"))),
get(CODE_NAMESPACE)
);
assert_eq!(Some(AnyValue::Int(101)), get(CODE_LINENO));
}

#[test]
fn test_flush() {
let exporter = InMemoryLogsExporter::default();
Expand Down
33 changes: 2 additions & 31 deletions opentelemetry-otlp/src/metric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use opentelemetry_sdk::{
metrics::{
data::{ResourceMetrics, Temporality},
exporter::PushMetricsExporter,
reader::{DefaultTemporalitySelector, TemporalitySelector},
reader::{DefaultTemporalitySelector, DeltaTemporalitySelector, TemporalitySelector},
InstrumentKind, PeriodicReader, SdkMeterProvider,
},
runtime::Runtime,
Expand Down Expand Up @@ -169,7 +169,7 @@ where
///
/// [exporter-docs]: https://github.com/open-telemetry/opentelemetry-specification/blob/a1c13d59bb7d0fb086df2b3e1eaec9df9efef6cc/specification/metrics/sdk_exporters/otlp.md#additional-configuration
pub fn with_delta_temporality(self) -> Self {
self.with_temporality_selector(DeltaTemporalitySelector)
self.with_temporality_selector(DeltaTemporalitySelector::new())
}
}

Expand Down Expand Up @@ -237,35 +237,6 @@ impl<RT, EB: Debug> Debug for OtlpMetricPipeline<RT, EB> {
}
}

/// A temporality selector that returns [`Delta`][Temporality::Delta] for all
/// instruments except `UpDownCounter` and `ObservableUpDownCounter`.
///
/// This temporality selector is equivalent to OTLP Metrics Exporter's
/// `Delta` temporality preference (see [its documentation][exporter-docs]).
///
/// [exporter-docs]: https://github.com/open-telemetry/opentelemetry-specification/blob/a1c13d59bb7d0fb086df2b3e1eaec9df9efef6cc/specification/metrics/sdk_exporters/otlp.md#additional-configuration
#[derive(Debug)]
struct DeltaTemporalitySelector;

impl TemporalitySelector for DeltaTemporalitySelector {
#[rustfmt::skip]
fn temporality(&self, kind: InstrumentKind) -> Temporality {
match kind {
InstrumentKind::Counter
| InstrumentKind::Histogram
| InstrumentKind::ObservableCounter
| InstrumentKind::Gauge
| InstrumentKind::ObservableGauge => {
Temporality::Delta
}
InstrumentKind::UpDownCounter
| InstrumentKind::ObservableUpDownCounter => {
Temporality::Cumulative
}
}
}
}

/// An interface for OTLP metrics clients
#[async_trait]
pub trait MetricsClient: fmt::Debug + Send + Sync + 'static {
Expand Down
24 changes: 1 addition & 23 deletions opentelemetry-sdk/benches/metric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use opentelemetry_sdk::{
metrics::{
data::{ResourceMetrics, Temporality},
new_view,
reader::{MetricReader, TemporalitySelector},
reader::{DeltaTemporalitySelector, MetricReader, TemporalitySelector},
Aggregation, Instrument, InstrumentKind, ManualReader, Pipeline, SdkMeterProvider, Stream,
View,
},
Expand Down Expand Up @@ -44,28 +44,6 @@ impl MetricReader for SharedReader {
}
}

/// Configure delta temporality for all [InstrumentKind]
///
/// [Temporality::Delta] will be used for all instrument kinds if this
/// [TemporalitySelector] is used.
#[derive(Clone, Default, Debug)]
pub struct DeltaTemporalitySelector {
pub(crate) _private: (),
}

impl DeltaTemporalitySelector {
/// Create a new default temporality selector.
pub fn new() -> Self {
Self::default()
}
}

impl TemporalitySelector for DeltaTemporalitySelector {
fn temporality(&self, _kind: InstrumentKind) -> Temporality {
Temporality::Delta
}
}

// * Summary *

// rustc 1.68.0 (2c8cc3432 2023-03-06)
Expand Down
30 changes: 3 additions & 27 deletions opentelemetry-sdk/src/metrics/instrument.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{borrow::Cow, collections::HashSet, sync::Arc};

use opentelemetry::{
metrics::{AsyncInstrument, SyncCounter, SyncGauge, SyncHistogram, SyncUpDownCounter},
metrics::{AsyncInstrument, SyncInstrument},
Key, KeyValue,
};

Expand Down Expand Up @@ -252,32 +252,8 @@ pub(crate) struct ResolvedMeasures<T> {
pub(crate) measures: Vec<Arc<dyn Measure<T>>>,
}

impl<T: Copy + 'static> SyncCounter<T> for ResolvedMeasures<T> {
fn add(&self, val: T, attrs: &[KeyValue]) {
for measure in &self.measures {
measure.call(val, attrs)
}
}
}

impl<T: Copy + 'static> SyncUpDownCounter<T> for ResolvedMeasures<T> {
fn add(&self, val: T, attrs: &[KeyValue]) {
for measure in &self.measures {
measure.call(val, attrs)
}
}
}

impl<T: Copy + 'static> SyncGauge<T> for ResolvedMeasures<T> {
fn record(&self, val: T, attrs: &[KeyValue]) {
for measure in &self.measures {
measure.call(val, attrs)
}
}
}

impl<T: Copy + 'static> SyncHistogram<T> for ResolvedMeasures<T> {
fn record(&self, val: T, attrs: &[KeyValue]) {
impl<T: Copy + 'static> SyncInstrument<T> for ResolvedMeasures<T> {
fn measure(&self, val: T, attrs: &[KeyValue]) {
for measure in &self.measures {
measure.call(val, attrs)
}
Expand Down
27 changes: 3 additions & 24 deletions opentelemetry-sdk/src/metrics/noop.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use opentelemetry::{
metrics::{
AsyncInstrument, InstrumentProvider, SyncCounter, SyncGauge, SyncHistogram,
SyncUpDownCounter,
},
metrics::{AsyncInstrument, InstrumentProvider, SyncInstrument},
KeyValue,
};

Expand Down Expand Up @@ -34,26 +31,8 @@ impl NoopSyncInstrument {
}
}

impl<T> SyncCounter<T> for NoopSyncInstrument {
fn add(&self, _value: T, _attributes: &[KeyValue]) {
// Ignored
}
}

impl<T> SyncUpDownCounter<T> for NoopSyncInstrument {
fn add(&self, _value: T, _attributes: &[KeyValue]) {
// Ignored
}
}

impl<T> SyncHistogram<T> for NoopSyncInstrument {
fn record(&self, _value: T, _attributes: &[KeyValue]) {
// Ignored
}
}

impl<T> SyncGauge<T> for NoopSyncInstrument {
fn record(&self, _value: T, _attributes: &[KeyValue]) {
impl<T> SyncInstrument<T> for NoopSyncInstrument {
fn measure(&self, _value: T, _attributes: &[KeyValue]) {
// Ignored
}
}
Expand Down
38 changes: 38 additions & 0 deletions opentelemetry-sdk/src/metrics/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,41 @@ impl TemporalitySelector for DefaultTemporalitySelector {
Temporality::Cumulative
}
}

/// A temporality selector that returns [`Delta`][Temporality::Delta] for all
/// instruments except `UpDownCounter` and `ObservableUpDownCounter`.
///
/// This temporality selector is equivalent to OTLP Metrics Exporter's
/// `Delta` temporality preference (see [its documentation][exporter-docs]).
///
/// [exporter-docs]: https://github.com/open-telemetry/opentelemetry-specification/blob/a1c13d59bb7d0fb086df2b3e1eaec9df9efef6cc/specification/metrics/sdk_exporters/otlp.md#additional-configuration
#[derive(Clone, Default, Debug)]
pub struct DeltaTemporalitySelector {
pub(crate) _private: (),
}

impl DeltaTemporalitySelector {
/// Create a new default temporality selector.
pub fn new() -> Self {
Self::default()
}
}

impl TemporalitySelector for DeltaTemporalitySelector {
#[rustfmt::skip]
fn temporality(&self, kind: InstrumentKind) -> Temporality {
match kind {
InstrumentKind::Counter
| InstrumentKind::Histogram
| InstrumentKind::ObservableCounter
| InstrumentKind::Gauge
| InstrumentKind::ObservableGauge => {
Temporality::Delta
}
InstrumentKind::UpDownCounter
| InstrumentKind::ObservableUpDownCounter => {
Temporality::Cumulative
}
}
}
}
3 changes: 2 additions & 1 deletion opentelemetry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

- Bump MSRV to 1.70 [#2179](https://github.com/open-telemetry/opentelemetry-rust/pull/2179)
- Add `LogRecord::set_trace_context`; an optional method conditional on the `trace` feature for setting trace context on a log record.
- Remove unnecessary public methods named `as_any` from `AsyncInstrument` trait and the implementing instruments: `ObservableCounter`, `ObservableGauge`, and `ObservableUpDownCounter` [#2187](https://github.com/open-telemetry/opentelemetry-rust/issues/2187)
- Removed unnecessary public methods named `as_any` from `AsyncInstrument` trait and the implementing instruments: `ObservableCounter`, `ObservableGauge`, and `ObservableUpDownCounter` [#2187](https://github.com/open-telemetry/opentelemetry-rust/issues/2187)
- Introduced `SyncInstrument` trait to replace the individual synchronous instrument traits (`SyncCounter`, `SyncGauge`, `SyncHistogram`, `SyncUpDownCounter`) which are meant for SDK implementation. [#2207](https://github.com/open-telemetry/opentelemetry-rust/issues/2207)

## v0.26.0
Released 2024-Sep-30
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ pub enum Value {
}

/// Wrapper for string-like values
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct StringValue(OtelString);

impl fmt::Debug for StringValue {
Expand Down
Loading

0 comments on commit a566aac

Please sign in to comment.