Skip to content

Commit

Permalink
bump opentelemetry from 0.19.0 to 0.20.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sunli829 committed Aug 13, 2023
1 parent a7aca56 commit 5ed753e
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 89 deletions.
8 changes: 4 additions & 4 deletions examples/poem/opentelemetry-jaeger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ edition.workspace = true
publish.workspace = true

[dependencies]
poem = { workspace = true, features = ["opentelemetry", "prometheus"] }
poem = { workspace = true, features = ["opentelemetry"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
tracing-subscriber.workspace = true
opentelemetry = { version = "0.19.0", features = ["metrics"] }
opentelemetry-http = { version = "0.8.0" }
opentelemetry-jaeger = { version = "0.18.0", features = [
opentelemetry = { version = "0.20.0", features = ["metrics"] }
opentelemetry-http = { version = "0.9.0" }
opentelemetry-jaeger = { version = "0.19.0", features = [
"rt-tokio",
"collector_client",
"hyper_collector_client",
Expand Down
2 changes: 0 additions & 2 deletions examples/poem/opentelemetry-jaeger/src/server1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use opentelemetry::{
};
use opentelemetry_http::HeaderInjector;
use poem::{
endpoint::PrometheusExporter,
get, handler,
http::Method,
listener::TcpListener,
Expand Down Expand Up @@ -77,7 +76,6 @@ async fn main() -> Result<(), std::io::Error> {

let app = Route::new()
.at("/api1", get(index))
.at("/metrics", PrometheusExporter::new())
.data(tracer.clone())
.with(OpenTelemetryMetrics::new())
.with(OpenTelemetryTracing::new(tracer));
Expand Down
2 changes: 0 additions & 2 deletions examples/poem/opentelemetry-jaeger/src/server2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use opentelemetry::{
sdk::{propagation::TraceContextPropagator, trace::Tracer},
};
use poem::{
endpoint::PrometheusExporter,
get, handler,
listener::TcpListener,
middleware::{OpenTelemetryMetrics, OpenTelemetryTracing},
Expand Down Expand Up @@ -36,7 +35,6 @@ async fn main() -> Result<(), std::io::Error> {

let app = Route::new()
.at("/api2", get(index))
.at("/metrics", PrometheusExporter::new())
.data(tracer.clone())
.with(OpenTelemetryMetrics::new())
.with(OpenTelemetryTracing::new(tracer));
Expand Down
8 changes: 4 additions & 4 deletions poem/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ libcookie = { package = "cookie", version = "0.16", features = [
"key-expansion",
"secure",
], optional = true }
opentelemetry-http = { version = "0.8.0", optional = true }
opentelemetry-semantic-conventions = { version = "0.11.0", optional = true }
opentelemetry-prometheus = { version = "0.12.0", optional = true }
opentelemetry-http = { version = "0.9.0", optional = true }
opentelemetry-semantic-conventions = { version = "0.12.0", optional = true }
opentelemetry-prometheus = { version = "0.13.0", optional = true }
libprometheus = { package = "prometheus", version = "0.13.0", optional = true }
libopentelemetry = { package = "opentelemetry", version = "0.19.0", features = [
libopentelemetry = { package = "opentelemetry", version = "0.20.0", features = [
"metrics",
], optional = true }
libtempfile = { package = "tempfile", version = "3.2.0", optional = true }
Expand Down
66 changes: 6 additions & 60 deletions poem/src/endpoint/prometheus_exporter.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
use std::collections::HashMap;

use libopentelemetry::sdk::{
export::metrics::aggregation,
metrics::{controllers, controllers::BasicController, processors, selectors},
};
use libprometheus::{Encoder, Registry, TextEncoder};

use crate::{
Expand Down Expand Up @@ -32,56 +26,13 @@ use crate::{
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "prometheus")))]
pub struct PrometheusExporter {
controller: BasicController,
prefix: Option<String>,
labels: HashMap<String, String>,
}

impl Default for PrometheusExporter {
fn default() -> Self {
Self::new()
}
registry: Registry,
}

impl PrometheusExporter {
/// Create a `PrometheusExporter` endpoint.
pub fn new() -> Self {
let controller = controllers::basic(processors::factory(
selectors::simple::histogram([1.0, 2.0, 5.0, 10.0, 20.0, 50.0]),
aggregation::cumulative_temporality_selector(),
))
.build();

Self {
controller,
prefix: None,
labels: HashMap::new(),
}
}

/// Create a `PrometheusExporter` endpoint with a controller.
pub fn with_controller(controller: BasicController) -> Self {
Self {
controller,
prefix: None,
labels: HashMap::new(),
}
}

/// Set a common namespace for all registered collectors.
#[must_use]
pub fn prefix(self, prefix: impl Into<String>) -> Self {
Self {
prefix: Some(prefix.into()),
..self
}
}

/// Add a common label for all registered collectors.
#[must_use]
pub fn label(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(name.into(), value.into());
self
pub fn new(registry: Registry) -> Self {
Self { registry }
}
}

Expand All @@ -90,19 +41,14 @@ impl IntoEndpoint for PrometheusExporter {

fn into_endpoint(self) -> Self::Endpoint {
PrometheusExporterEndpoint {
exporter: opentelemetry_prometheus::exporter(self.controller)
.with_registry(
Registry::new_custom(self.prefix, Some(self.labels))
.expect("create prometheus registry"),
)
.init(),
registry: self.registry.clone(),
}
}
}

#[doc(hidden)]
pub struct PrometheusExporterEndpoint {
exporter: opentelemetry_prometheus::PrometheusExporter,
registry: Registry,
}

#[async_trait::async_trait]
Expand All @@ -115,7 +61,7 @@ impl Endpoint for PrometheusExporterEndpoint {
}

let encoder = TextEncoder::new();
let metric_families = self.exporter.registry().gather();
let metric_families = self.registry.gather();
let mut result = Vec::new();
match encoder.encode(&metric_families, &mut result) {
Ok(()) => Ok(Response::builder().content_type("text/plain").body(result)),
Expand Down
18 changes: 8 additions & 10 deletions poem/src/middleware/opentelemetry_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::time::Instant;
use libopentelemetry::{
global,
metrics::{Counter, Histogram, Unit},
Context, Key,
Key,
};
use opentelemetry_semantic_conventions::trace;

Expand Down Expand Up @@ -74,11 +74,9 @@ impl<E: Endpoint> Endpoint for OpenTelemetryMetricsEndpoint<E> {
type Output = Response;

async fn call(&self, req: Request) -> Result<Self::Output> {
let cx = Context::new();

let mut labels = Vec::with_capacity(3);
labels.push(trace::HTTP_METHOD.string(req.method().to_string()));
labels.push(trace::HTTP_URL.string(req.original_uri().to_string()));
labels.push(trace::HTTP_REQUEST_METHOD.string(req.method().to_string()));
labels.push(trace::URL_FULL.string(req.original_uri().to_string()));

let s = Instant::now();
let res = self.inner.call(req).await.map(IntoResponse::into_response);
Expand All @@ -91,23 +89,23 @@ impl<E: Endpoint> Endpoint for OpenTelemetryMetricsEndpoint<E> {
labels.push(HTTP_PATH_PATTERN.string(path_pattern.0.to_string()));
}

labels.push(trace::HTTP_STATUS_CODE.i64(resp.status().as_u16() as i64));
labels.push(trace::HTTP_RESPONSE_STATUS_CODE.i64(resp.status().as_u16() as i64));
}
Err(err) => {
if let Some(path_pattern) = err.data::<PathPattern>() {
const HTTP_PATH_PATTERN: Key = Key::from_static_str("http.path_pattern");
labels.push(HTTP_PATH_PATTERN.string(path_pattern.0.to_string()));
}

labels.push(trace::HTTP_STATUS_CODE.i64(err.status().as_u16() as i64));
self.error_count.add(&cx, 1, &labels);
labels.push(trace::HTTP_RESPONSE_STATUS_CODE.i64(err.status().as_u16() as i64));
self.error_count.add(1, &labels);
labels.push(trace::EXCEPTION_MESSAGE.string(err.to_string()));
}
}

self.request_count.add(&cx, 1, &labels);
self.request_count.add(1, &labels);
self.duration
.record(&cx, elapsed.as_secs_f64() * 1000.0, &labels);
.record(elapsed.as_secs_f64() * 1000.0, &labels);

res
}
Expand Down
18 changes: 11 additions & 7 deletions poem/src/middleware/opentelemetry_tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ where
attributes.push(resource::TELEMETRY_SDK_NAME.string(env!("CARGO_CRATE_NAME")));
attributes.push(resource::TELEMETRY_SDK_VERSION.string(env!("CARGO_PKG_VERSION")));
attributes.push(resource::TELEMETRY_SDK_LANGUAGE.string("rust"));
attributes.push(trace::HTTP_METHOD.string(req.method().to_string()));
attributes.push(trace::HTTP_URL.string(req.original_uri().to_string()));
attributes.push(trace::HTTP_CLIENT_IP.string(remote_addr));
attributes.push(trace::HTTP_FLAVOR.string(format!("{:?}", req.version())));
attributes.push(trace::HTTP_REQUEST_METHOD.string(req.method().to_string()));
attributes.push(trace::URL_FULL.string(req.original_uri().to_string()));
attributes.push(trace::CLIENT_ADDRESS.string(remote_addr));
attributes.push(trace::NETWORK_PROTOCOL_VERSION.string(format!("{:?}", req.version())));

if let Some(path_pattern) = req.data::<PathPattern>() {
const HTTP_PATH_PATTERN: Key = Key::from_static_str("http.path_pattern");
Expand All @@ -105,18 +105,22 @@ where
Ok(resp) => {
let resp = resp.into_response();
span.add_event("request.completed".to_string(), vec![]);
span.set_attribute(trace::HTTP_STATUS_CODE.i64(resp.status().as_u16() as i64));
span.set_attribute(
trace::HTTP_RESPONSE_STATUS_CODE.i64(resp.status().as_u16() as i64),
);
if let Some(content_length) =
resp.headers().typed_get::<headers::ContentLength>()
{
span.set_attribute(
trace::HTTP_RESPONSE_CONTENT_LENGTH.i64(content_length.0 as i64),
trace::HTTP_RESPONSE_BODY_SIZE.i64(content_length.0 as i64),
);
}
Ok(resp)
}
Err(err) => {
span.set_attribute(trace::HTTP_STATUS_CODE.i64(err.status().as_u16() as i64));
span.set_attribute(
trace::HTTP_RESPONSE_STATUS_CODE.i64(err.status().as_u16() as i64),
);
span.add_event(
"request.error".to_string(),
vec![trace::EXCEPTION_MESSAGE.string(err.to_string())],
Expand Down

0 comments on commit 5ed753e

Please sign in to comment.