Skip to content

Commit

Permalink
Unify builders across signals
Browse files Browse the repository at this point in the history
  • Loading branch information
stormshield-fabs committed Oct 18, 2024
1 parent f677458 commit 8b09a51
Show file tree
Hide file tree
Showing 20 changed files with 206 additions and 502 deletions.
11 changes: 5 additions & 6 deletions opentelemetry-appender-log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@
use log::{Level, Metadata, Record};
use opentelemetry::{
logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity},
Key,
InstrumentationLibrary, Key,
};
#[cfg(feature = "experimental_metadata_attributes")]
use opentelemetry_semantic_conventions::attribute::{CODE_FILEPATH, CODE_LINENO, CODE_NAMESPACE};
use std::borrow::Cow;
use std::sync::Arc;

pub struct OpenTelemetryLogBridge<P, L>
where
Expand Down Expand Up @@ -170,11 +170,10 @@ where
L: Logger + Send + Sync,
{
pub fn new(provider: &P) -> Self {
let library =
Arc::new(InstrumentationLibrary::builder("opentelemetry-log-appender").build());
OpenTelemetryLogBridge {
logger: provider
.logger_builder("opentelemetry-log-appender")
.with_version(Cow::Borrowed(env!("CARGO_PKG_VERSION")))
.build(),
logger: provider.library_logger(library),
_phantom: Default::default(),
}
}
Expand Down
13 changes: 8 additions & 5 deletions opentelemetry-appender-tracing/src/layer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use opentelemetry::{
logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity},
Key,
InstrumentationLibrary, Key,
};
use std::borrow::Cow;
use std::{borrow::Cow, sync::Arc};
use tracing_core::Level;
#[cfg(feature = "experimental_metadata_attributes")]
use tracing_core::Metadata;
Expand Down Expand Up @@ -136,11 +136,14 @@ where
L: Logger + Send + Sync,
{
pub fn new(provider: &P) -> Self {
OpenTelemetryTracingBridge {
logger: provider
.logger_builder(INSTRUMENTATION_LIBRARY_NAME)
let library = Arc::new(
InstrumentationLibrary::builder(INSTRUMENTATION_LIBRARY_NAME)
.with_version(Cow::Borrowed(env!("CARGO_PKG_VERSION")))
.build(),
);

OpenTelemetryTracingBridge {
logger: provider.library_logger(library),
_phantom: Default::default(),
}
}
Expand Down
20 changes: 9 additions & 11 deletions opentelemetry-otlp/examples/basic-otlp-http/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use opentelemetry::{
global,
metrics::MetricsError,
trace::{TraceContextExt, TraceError, Tracer, TracerProvider as _},
KeyValue,
InstrumentationLibrary, KeyValue,
};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::Protocol;
Expand All @@ -13,7 +13,7 @@ use opentelemetry_sdk::{
logs::{self as sdklogs},
Resource,
};
use std::error::Error;
use std::{error::Error, sync::Arc};
use tracing::info;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
Expand Down Expand Up @@ -121,16 +121,14 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
.init();

let common_scope_attributes = vec![KeyValue::new("scope-key", "scope-value")];
let tracer = global::tracer_provider()
.tracer_builder("basic")
.with_attributes(common_scope_attributes.clone())
.build();
let meter = global::meter_with_version(
"basic",
Some("v1.0"),
Some("schema_url"),
Some(common_scope_attributes.clone()),
let library = Arc::new(
InstrumentationLibrary::builder("basic")
.with_version("1.0")
.with_attributes(common_scope_attributes.clone())
.build(),
);
let tracer = global::tracer_provider().library_tracer(library.clone());
let meter = global::library_meter(library);

let counter = meter
.u64_counter("test_counter")
Expand Down
26 changes: 11 additions & 15 deletions opentelemetry-otlp/examples/basic-otlp/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
use once_cell::sync::Lazy;
use opentelemetry::global;
use opentelemetry::logs::LogError;
use opentelemetry::metrics::MetricsError;
use opentelemetry::trace::{TraceError, TracerProvider};
use opentelemetry::{
trace::{TraceContextExt, Tracer},
KeyValue,
};
use opentelemetry::trace::{TraceContextExt, TraceError, Tracer, TracerProvider};
use opentelemetry::KeyValue;
use opentelemetry::{global, InstrumentationLibrary};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{ExportConfig, WithExportConfig};
use opentelemetry_sdk::trace::Config;
use opentelemetry_sdk::{runtime, trace as sdktrace, Resource};
use std::error::Error;
use std::sync::Arc;
use tracing::info;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
Expand Down Expand Up @@ -112,16 +110,14 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
.init();

let common_scope_attributes = vec![KeyValue::new("scope-key", "scope-value")];
let tracer = global::tracer_provider()
.tracer_builder("basic")
.with_attributes(common_scope_attributes.clone())
.build();
let meter = global::meter_with_version(
"basic",
Some("v1.0"),
Some("schema_url"),
Some(common_scope_attributes.clone()),
let library = Arc::new(
InstrumentationLibrary::builder("basic")
.with_version("1.0")
.with_attributes(common_scope_attributes.clone())
.build(),
);
let tracer = global::tracer_provider().library_tracer(library.clone());
let meter = global::library_meter(library);

let counter = meter
.u64_counter("test_counter")
Expand Down
41 changes: 4 additions & 37 deletions opentelemetry-sdk/src/logs/log_emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use opentelemetry::{
#[cfg(feature = "logs_level_enabled")]
use opentelemetry::logs::Severity;

use std::{
borrow::Cow,
sync::{atomic::Ordering, Arc},
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::{sync::atomic::AtomicBool, time::SystemTime};
use std::time::SystemTime;

use once_cell::sync::Lazy;

Expand Down Expand Up @@ -45,42 +45,9 @@ pub struct LoggerProvider {
inner: Arc<LoggerProviderInner>,
}

/// Default logger name if empty string is provided.
const DEFAULT_COMPONENT_NAME: &str = "rust.opentelemetry.io/sdk/logger";

impl opentelemetry::logs::LoggerProvider for LoggerProvider {
type Logger = Logger;

/// Create a new versioned `Logger` instance.
fn versioned_logger(
&self,
name: impl Into<Cow<'static, str>>,
version: Option<Cow<'static, str>>,
schema_url: Option<Cow<'static, str>>,
attributes: Option<Vec<opentelemetry::KeyValue>>,
) -> Logger {
let name = name.into();
let component_name = if name.is_empty() {
Cow::Borrowed(DEFAULT_COMPONENT_NAME)
} else {
name
};

let mut builder = self.logger_builder(component_name);

if let Some(v) = version {
builder = builder.with_version(v);
}
if let Some(s) = schema_url {
builder = builder.with_schema_url(s);
}
if let Some(a) = attributes {
builder = builder.with_attributes(a);
}

builder.build()
}

fn library_logger(&self, library: Arc<InstrumentationLibrary>) -> Self::Logger {
// If the provider is shutdown, new logger will refer a no-op logger provider.
if self.inner.is_shutdown.load(Ordering::Relaxed) {
Expand Down
35 changes: 8 additions & 27 deletions opentelemetry-sdk/src/logs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ mod tests {
use opentelemetry::{logs::AnyValue, Key, KeyValue};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::sync::Arc;

#[test]
fn logging_sdk_test() {
Expand Down Expand Up @@ -104,36 +105,16 @@ mod tests {
#[test]
fn logger_attributes() {
let provider = LoggerProvider::builder().build();
let logger = provider
.logger_builder("test_logger")
.with_schema_url("https://opentelemetry.io/schema/1.0.0")
.with_attributes(vec![(KeyValue::new("test_k", "test_v"))])
.build();
let instrumentation_library = logger.instrumentation_library();
let attributes = &instrumentation_library.attributes;
assert_eq!(instrumentation_library.name, "test_logger");
assert_eq!(
instrumentation_library.schema_url,
Some("https://opentelemetry.io/schema/1.0.0".into())
);
assert_eq!(attributes.len(), 1);
assert_eq!(attributes[0].key, "test_k".into());
assert_eq!(attributes[0].value, "test_v".into());
}

#[test]
#[allow(deprecated)]
fn versioned_logger_options() {
let provider = LoggerProvider::builder().build();
let logger = provider.versioned_logger(
"test_logger",
Some("v1.2.3".into()),
Some("https://opentelemetry.io/schema/1.0.0".into()),
Some(vec![(KeyValue::new("test_k", "test_v"))]),
let library = Arc::new(
InstrumentationLibrary::builder("test_logger")
.with_schema_url("https://opentelemetry.io/schema/1.0.0")
.with_attributes(vec![(KeyValue::new("test_k", "test_v"))])
.build(),
);
let logger = provider.library_logger(library);
let instrumentation_library = logger.instrumentation_library();
let attributes = &instrumentation_library.attributes;
assert_eq!(instrumentation_library.version, Some("v1.2.3".into()));
assert_eq!(instrumentation_library.name, "test_logger");
assert_eq!(
instrumentation_library.schema_url,
Some("https://opentelemetry.io/schema/1.0.0".into())
Expand Down
75 changes: 38 additions & 37 deletions opentelemetry-sdk/src/metrics/meter_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{
use opentelemetry::{
global,
metrics::{Meter, MeterProvider, MetricsError, Result},
KeyValue,
InstrumentationLibrary,
};

use crate::{instrumentation::Scope, Resource};
Expand Down Expand Up @@ -145,34 +145,14 @@ impl Drop for SdkMeterProviderInner {
}
}
impl MeterProvider for SdkMeterProvider {
fn versioned_meter(
&self,
name: &'static str,
version: Option<&'static str>,
schema_url: Option<&'static str>,
attributes: Option<Vec<KeyValue>>,
) -> Meter {
fn library_meter(&self, library: Arc<InstrumentationLibrary>) -> Meter {
if self.inner.is_shutdown.load(Ordering::Relaxed) {
return Meter::new(Arc::new(NoopMeter::new()));
}

let mut builder = Scope::builder(name);

if let Some(v) = version {
builder = builder.with_version(v);
}
if let Some(s) = schema_url {
builder = builder.with_schema_url(s);
}
if let Some(a) = attributes {
builder = builder.with_attributes(a);
}

let scope = builder.build();

if let Ok(mut meters) = self.inner.meters.lock() {
let meter = meters
.entry(scope)
.entry(InstrumentationLibrary::clone(&library))
.or_insert_with_key(|scope| {
Arc::new(SdkMeter::new(scope.clone(), self.inner.pipes.clone()))
})
Expand Down Expand Up @@ -260,10 +240,11 @@ mod tests {
};
use crate::testing::metrics::metric_reader::TestMetricReader;
use crate::Resource;
use opentelemetry::global;
use opentelemetry::metrics::MeterProvider;
use opentelemetry::{global, InstrumentationLibrary};
use opentelemetry::{Key, KeyValue, Value};
use std::env;
use std::sync::Arc;

#[test]
fn test_meter_provider_resource() {
Expand Down Expand Up @@ -454,21 +435,41 @@ mod tests {
let _meter1 = provider.meter("test");
let _meter2 = provider.meter("test");
assert_eq!(provider.inner.meters.lock().unwrap().len(), 1);
let _meter3 =
provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);
let _meter4 =
provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);
let _meter5 =
provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);

let library = Arc::new(
InstrumentationLibrary::builder("test")
.with_version("1.0.0")
.with_schema_url("http://example.com")
.build(),
);

let _meter3 = provider.library_meter(library.clone());
let _meter4 = provider.library_meter(library.clone());
let _meter5 = provider.library_meter(library);
assert_eq!(provider.inner.meters.lock().unwrap().len(), 2);

// the below are different meters, as meter names are case sensitive
let _meter6 =
provider.versioned_meter("ABC", Some("1.0.0"), Some("http://example.com"), None);
let _meter7 =
provider.versioned_meter("Abc", Some("1.0.0"), Some("http://example.com"), None);
let _meter8 =
provider.versioned_meter("abc", Some("1.0.0"), Some("http://example.com"), None);
// these are different meters because meter names are case sensitive
let library = Arc::new(
InstrumentationLibrary::builder("ABC")
.with_version("1.0.0")
.with_schema_url("http://example.com")
.build(),
);
let _meter6 = provider.library_meter(library);
let library = Arc::new(
InstrumentationLibrary::builder("Abc")
.with_version("1.0.0")
.with_schema_url("http://example.com")
.build(),
);
let _meter7 = provider.library_meter(library);
let library = Arc::new(
InstrumentationLibrary::builder("abc")
.with_version("1.0.0")
.with_schema_url("http://example.com")
.build(),
);
let _meter8 = provider.library_meter(library);
assert_eq!(provider.inner.meters.lock().unwrap().len(), 5);
}
}
Loading

0 comments on commit 8b09a51

Please sign in to comment.