Skip to content

Commit

Permalink
Merge branch 'main' into cijothomas/simplelog-static
Browse files Browse the repository at this point in the history
  • Loading branch information
cijothomas authored Dec 2, 2024
2 parents c41d326 + a3c469b commit dc0257d
Show file tree
Hide file tree
Showing 41 changed files with 514 additions and 207 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:
- rust: stable
os: actuated-arm64-4cpu-16gb
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.rust == 'beta' }}
steps:
- name: Free disk space
if: ${{ matrix.os == 'ubuntu-latest'}}
Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,19 @@ observability tools.

## Project Status

The table below summarizes the overall status of each component. Some components
include unstable features, which are documented in their respective crate
documentation.

| Signal/Component | Overall Status |
| -------------------- | ------------------ |
| Logs-API | RC* |
| Logs-SDK | Beta |
| Logs-OTLP Exporter | Beta |
| Logs-Appender-Tracing | Beta |
| Metrics-API | RC |
| Metrics-SDK | Beta |
| Metrics-OTLP Exporter | Beta |
| Metrics-SDK | Beta |
| Metrics-OTLP Exporter | Beta |
| Traces-API | Beta |
| Traces-SDK | Beta |
| Traces-OTLP Exporter | Beta |
Expand Down
5 changes: 1 addition & 4 deletions examples/metrics-basic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@ license = "Apache-2.0"
publish = false

[dependencies]
opentelemetry = { path = "../../opentelemetry", features = ["metrics", "otel_unstable"] }
opentelemetry = { path = "../../opentelemetry", features = ["metrics"] }
opentelemetry_sdk = { path = "../../opentelemetry-sdk", features = ["metrics", "rt-tokio"] }
opentelemetry-stdout = { path = "../../opentelemetry-stdout", features = ["metrics"]}
tokio = { workspace = true, features = ["full"] }
serde_json = { workspace = true }

[features]
default = ["otel_unstable"]
otel_unstable = ["opentelemetry/otel_unstable"]
2 changes: 1 addition & 1 deletion examples/self-diagnostics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ opentelemetry-stdout = { path = "../../opentelemetry-stdout"}
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true, features = ["std"]}
tracing-core = { workspace = true }
tracing-subscriber = { version = "0.3.18", features = ["env-filter","registry", "std"]}
tracing-subscriber = { workspace = true, features = ["env-filter","registry", "std", "fmt"]}
18 changes: 13 additions & 5 deletions examples/self-diagnostics/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use opentelemetry::global;
use opentelemetry::KeyValue;
use opentelemetry_sdk::metrics::PeriodicReader;
use opentelemetry_sdk::Resource;
use std::error::Error;
use tracing::info;
use tracing_subscriber::fmt;
Expand All @@ -13,6 +14,10 @@ fn init_meter_provider() -> opentelemetry_sdk::metrics::SdkMeterProvider {
let reader = PeriodicReader::builder(exporter, opentelemetry_sdk::runtime::Tokio).build();

let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
.with_resource(Resource::new([KeyValue::new(
"service.name",
"self-diagnostics-example",
)]))
.with_reader(reader)
.build();

Expand All @@ -26,7 +31,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// OpenTelemetry uses `tracing` crate for its internal logging. Unless a
// tracing subscriber is set, the logs will be discarded. In this example,
// we configure a `tracing` subscriber to:
// 1. Print logs of level INFO or higher to stdout using tracing's fmt layer.
// 1. Print logs of level DEBUG or higher to stdout using tracing's fmt layer.
// 2. Filter logs from OpenTelemetry's dependencies (like tonic, hyper,
// reqwest etc. which are commonly used by the OTLP exporter) to only print
// ERROR-level logs. This filtering helps reduce repetitive log messages
Expand All @@ -39,7 +44,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// Hence, one may use "add_directive("opentelemetry=off".parse().unwrap())"
// to turn off all logs from OpenTelemetry.

let filter = EnvFilter::new("info")
let filter = EnvFilter::new("debug")
.add_directive("hyper=error".parse().unwrap())
.add_directive("tonic=error".parse().unwrap())
.add_directive("h2=error".parse().unwrap())
Expand All @@ -54,11 +59,14 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
info!("Starting self-diagnostics example");

let meter = global::meter("example");
// Create a counter using an invalid name to trigger
// internal log about the same.
let counter = meter.u64_counter("my_counter with_space").build();
let counter = meter.u64_counter("my_counter").build();
counter.add(10, &[KeyValue::new("key", "value")]);

let _observable_counter = meter
.u64_observable_counter("my_observable_counter")
.with_callback(|observer| observer.observe(10, &[KeyValue::new("key", "value")]))
.build();

meter_provider.shutdown()?;
info!("Shutdown complete. Bye!");
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-appender-tracing/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl<'a, LR: LogRecord> EventVisitor<'a, LR> {
}
}

impl<'a, LR: LogRecord> tracing::field::Visit for EventVisitor<'a, LR> {
impl<LR: LogRecord> tracing::field::Visit for EventVisitor<'_, LR> {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
#[cfg(feature = "experimental_metadata_attributes")]
if is_duplicated_metadata(field.name()) {
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use opentelemetry::propagation::{Extractor, Injector};
/// for example usage.
pub struct HeaderInjector<'a>(pub &'a mut http::HeaderMap);

impl<'a> Injector for HeaderInjector<'a> {
impl Injector for HeaderInjector<'_> {
/// Set a key and value in the HeaderMap. Does nothing if the key or value are not valid inputs.
fn set(&mut self, key: &str, value: String) {
if let Ok(name) = http::header::HeaderName::from_bytes(key.as_bytes()) {
Expand All @@ -30,7 +30,7 @@ impl<'a> Injector for HeaderInjector<'a> {
/// for example usage.
pub struct HeaderExtractor<'a>(pub &'a http::HeaderMap);

impl<'a> Extractor for HeaderExtractor<'a> {
impl Extractor for HeaderExtractor<'_> {
/// Get a value for a key from the HeaderMap. If the value is not valid ASCII, returns None.
fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).and_then(|value| value.to_str().ok())
Expand Down
17 changes: 17 additions & 0 deletions opentelemetry-sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## vNext

## 0.27.1

Released 2024-Nov-27

- **DEPRECATED**:
- `trace::Config` methods are moving onto `TracerProvider` Builder to be consistent with other signals. See https://github.com/open-telemetry/opentelemetry-rust/pull/2303 for migration guide.
`trace::Config` is scheduled to be removed from public API in `v0.28.0`.
Expand All @@ -25,6 +29,19 @@
- Bug fix: Empty Logger names are retained as-is instead of replacing with
"rust.opentelemetry.io/sdk/logger"
[#2316](https://github.com/open-telemetry/opentelemetry-rust/pull/2316)

- `Logger::provider`: This method is deprecated as of version `0.27.1`. To be removed in `0.28.0`.
- `Logger::instrumentation_scope`: This method is deprecated as of version `0.27.1`. To be removed in `0.28.0`
Migration Guidance:
- These methods are intended for log appenders. Keep the clone of the provider handle, instead of depending on above methods.


- **Bug Fix:** Validates the `with_boundaries` bucket boundaries used in
Histograms. The boundaries provided by the user must not contain `f64::NAN`,
`f64::INFINITY` or `f64::NEG_INFINITY` and must be sorted in strictly
increasing order, and contain no duplicates. Instruments will not record
measurements if the boundaries are invalid.
[#2351](https://github.com/open-telemetry/opentelemetry-rust/pull/2351)

## 0.27.0

Expand Down
3 changes: 1 addition & 2 deletions opentelemetry-sdk/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "opentelemetry_sdk"
version = "0.27.0"
version = "0.27.1"
description = "The SDK for the OpenTelemetry metrics collection and distributed tracing framework"
homepage = "https://github.com/open-telemetry/opentelemetry-rust"
repository = "https://github.com/open-telemetry/opentelemetry-rust"
Expand All @@ -17,7 +17,6 @@ async-trait = { workspace = true, optional = true }
futures-channel = "0.3"
futures-executor = { workspace = true }
futures-util = { workspace = true, features = ["std", "sink", "async-await-macro"] }
once_cell = { workspace = true }
percent-encoding = { version = "2.0", optional = true }
rand = { workspace = true, features = ["std", "std_rng","small_rng"], optional = true }
glob = { version = "0.3.1", optional =true}
Expand Down
1 change: 0 additions & 1 deletion opentelemetry-sdk/src/export/logs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ impl<'a> LogBatch<'a> {
///
/// Note - this is not a public function, and should not be used directly. This would be
/// made private in the future.
pub fn new(data: &'a [(&'a LogRecord, &'a InstrumentationScope)]) -> LogBatch<'a> {
LogBatch { data }
}
Expand Down
66 changes: 44 additions & 22 deletions opentelemetry-sdk/src/logs/log_emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,24 @@ use std::{
borrow::Cow,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
Arc, OnceLock,
},
};

use once_cell::sync::Lazy;

// a no nop logger provider used as placeholder when the provider is shutdown
static NOOP_LOGGER_PROVIDER: Lazy<LoggerProvider> = Lazy::new(|| LoggerProvider {
inner: Arc::new(LoggerProviderInner {
processors: Vec::new(),
resource: Resource::empty(),
is_shutdown: AtomicBool::new(true),
}),
});
// TODO - replace it with LazyLock once it is stable
static NOOP_LOGGER_PROVIDER: OnceLock<LoggerProvider> = OnceLock::new();

#[inline]
fn noop_logger_provider() -> &'static LoggerProvider {
NOOP_LOGGER_PROVIDER.get_or_init(|| LoggerProvider {
inner: Arc::new(LoggerProviderInner {
processors: Vec::new(),
resource: Resource::empty(),
is_shutdown: AtomicBool::new(true),
}),
})
}

#[derive(Debug, Clone)]
/// Handles the creation and coordination of [`Logger`]s.
Expand Down Expand Up @@ -55,11 +59,19 @@ impl opentelemetry::logs::LoggerProvider for LoggerProvider {
fn logger_with_scope(&self, scope: InstrumentationScope) -> Self::Logger {
// If the provider is shutdown, new logger will refer a no-op logger provider.
if self.inner.is_shutdown.load(Ordering::Relaxed) {
return Logger::new(scope, NOOP_LOGGER_PROVIDER.clone());
otel_debug!(
name: "LoggerProvider.NoOpLoggerReturned",
logger_name = scope.name(),
);
return Logger::new(scope, noop_logger_provider().clone());
}
if scope.name().is_empty() {
otel_info!(name: "LoggerNameEmpty", message = "Logger name is empty; consider providing a meaningful name. Logger will function normally and the provided name will be used as-is.");
};
otel_debug!(
name: "LoggerProvider.NewLoggerReturned",
logger_name = scope.name(),
);
Logger::new(scope, self.clone())
}
}
Expand Down Expand Up @@ -88,6 +100,9 @@ impl LoggerProvider {

/// Shuts down this `LoggerProvider`
pub fn shutdown(&self) -> LogResult<()> {
otel_debug!(
name: "LoggerProvider.ShutdownInvokedByUser",
);
if self
.inner
.is_shutdown
Expand Down Expand Up @@ -220,6 +235,10 @@ impl Builder {
for processor in logger_provider.log_processors() {
processor.set_resource(logger_provider.resource());
}

otel_debug!(
name: "LoggerProvider.Built",
);
logger_provider
}
}
Expand All @@ -238,11 +257,19 @@ impl Logger {
Logger { scope, provider }
}

#[deprecated(
since = "0.27.1",
note = "This method was intended for appender developers, but has no defined use-case in typical workflows. It is deprecated and will be removed in the next major release."
)]
/// LoggerProvider associated with this logger.
pub fn provider(&self) -> &LoggerProvider {
&self.provider
}

#[deprecated(
since = "0.27.1",
note = "This method was intended for appender developers, but has no defined use-case in typical workflows. It is deprecated and will be removed in the next major release."
)]
/// Instrumentation scope of this logger.
pub fn instrumentation_scope(&self) -> &InstrumentationScope {
&self.scope
Expand All @@ -258,7 +285,7 @@ impl opentelemetry::logs::Logger for Logger {

/// Emit a `LogRecord`.
fn emit(&self, mut record: Self::LogRecord) {
let provider = self.provider();
let provider = &self.provider;
let processors = provider.log_processors();

//let mut log_record = record;
Expand All @@ -277,22 +304,17 @@ impl opentelemetry::logs::Logger for Logger {
}

for p in processors {
p.emit(&mut record, self.instrumentation_scope());
p.emit(&mut record, &self.scope);
}
}

#[cfg(feature = "spec_unstable_logs_enabled")]
fn event_enabled(&self, level: Severity, target: &str) -> bool {
let provider = self.provider();
let provider = &self.provider;

let mut enabled = false;
for processor in provider.log_processors() {
enabled = enabled
|| processor.event_enabled(
level,
target,
self.instrumentation_scope().name().as_ref(),
);
enabled = enabled || processor.event_enabled(level, target, self.scope.name().as_ref());
}
enabled
}
Expand Down Expand Up @@ -725,14 +747,14 @@ mod tests {
emitted_logs[0].clone().record.body,
Some(AnyValue::String("Testing empty logger name".into()))
);
assert_eq!(logger.instrumentation_scope().name(), "");
assert_eq!(logger.scope.name(), "");

// Assert the second log created through the scope
assert_eq!(
emitted_logs[1].clone().record.body,
Some(AnyValue::String("Testing empty logger scope name".into()))
);
assert_eq!(scoped_logger.instrumentation_scope().name(), "");
assert_eq!(scoped_logger.scope.name(), "");
}

#[derive(Debug)]
Expand Down
Loading

0 comments on commit dc0257d

Please sign in to comment.