Skip to content

Commit c948ac8

Browse files
committed
chore: update otlp exporter example
1 parent 8327c95 commit c948ac8

File tree

8 files changed

+88
-38
lines changed

8 files changed

+88
-38
lines changed

opentelemetry-otlp/examples/basic-otlp-http/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ bench = false
1515
[features]
1616
default = ["reqwest-blocking"]
1717
reqwest-blocking = ["opentelemetry-otlp/reqwest-blocking-client"]
18+
gzip = ["opentelemetry-otlp/gzip-http"]
19+
zstd = ["opentelemetry-otlp/zstd-http"]
1820

1921
[dependencies]
2022
opentelemetry = { path = "../../../opentelemetry" }

opentelemetry-otlp/examples/basic-otlp-http/src/main.rs

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use opentelemetry::{
55
};
66
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
77
use opentelemetry_otlp::WithExportConfig;
8+
#[cfg(any(feature = "gzip", feature = "zstd"))]
9+
use opentelemetry_otlp::{Compression, WithHttpConfig};
810
use opentelemetry_otlp::{LogExporter, MetricExporter, Protocol, SpanExporter};
911
use opentelemetry_sdk::Resource;
1012
use opentelemetry_sdk::{
@@ -27,9 +29,23 @@ fn get_resource() -> Resource {
2729
}
2830

2931
fn init_logs() -> SdkLoggerProvider {
30-
let exporter = LogExporter::builder()
32+
let mut exporter_builder = LogExporter::builder()
3133
.with_http()
32-
.with_protocol(Protocol::HttpBinary)
34+
.with_protocol(Protocol::HttpBinary);
35+
36+
#[cfg(feature = "gzip")]
37+
{
38+
exporter_builder = exporter_builder.with_compression(Compression::Gzip);
39+
println!("Using gzip compression for logs");
40+
}
41+
42+
#[cfg(all(feature = "zstd", not(feature = "gzip")))]
43+
{
44+
exporter_builder = exporter_builder.with_compression(Compression::Zstd);
45+
println!("Using zstd compression for logs");
46+
}
47+
48+
let exporter = exporter_builder
3349
.build()
3450
.expect("Failed to create log exporter");
3551

@@ -40,9 +56,23 @@ fn init_logs() -> SdkLoggerProvider {
4056
}
4157

4258
fn init_traces() -> SdkTracerProvider {
43-
let exporter = SpanExporter::builder()
59+
let mut exporter_builder = SpanExporter::builder()
4460
.with_http()
45-
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format
61+
.with_protocol(Protocol::HttpBinary); //can be changed to `Protocol::HttpJson` to export in JSON format
62+
63+
#[cfg(feature = "gzip")]
64+
{
65+
exporter_builder = exporter_builder.with_compression(Compression::Gzip);
66+
println!("Using gzip compression for traces");
67+
}
68+
69+
#[cfg(all(feature = "zstd", not(feature = "gzip")))]
70+
{
71+
exporter_builder = exporter_builder.with_compression(Compression::Zstd);
72+
println!("Using zstd compression for traces");
73+
}
74+
75+
let exporter = exporter_builder
4676
.build()
4777
.expect("Failed to create trace exporter");
4878

@@ -53,9 +83,23 @@ fn init_traces() -> SdkTracerProvider {
5383
}
5484

5585
fn init_metrics() -> SdkMeterProvider {
56-
let exporter = MetricExporter::builder()
86+
let mut exporter_builder = MetricExporter::builder()
5787
.with_http()
58-
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format
88+
.with_protocol(Protocol::HttpBinary); //can be changed to `Protocol::HttpJson` to export in JSON format
89+
90+
#[cfg(feature = "gzip")]
91+
{
92+
exporter_builder = exporter_builder.with_compression(Compression::Gzip);
93+
println!("Using gzip compression for metrics");
94+
}
95+
96+
#[cfg(all(feature = "zstd", not(feature = "gzip")))]
97+
{
98+
exporter_builder = exporter_builder.with_compression(Compression::Zstd);
99+
println!("Using zstd compression for metrics");
100+
}
101+
102+
let exporter = exporter_builder
59103
.build()
60104
.expect("Failed to create metric exporter");
61105

opentelemetry-otlp/src/exporter/http/logs.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ impl LogExporter for OtlpHttpClient {
2222
.method(Method::POST)
2323
.uri(&self.collector_endpoint)
2424
.header(CONTENT_TYPE, content_type);
25-
25+
2626
if let Some(encoding) = content_encoding {
2727
request_builder = request_builder.header("Content-Encoding", encoding);
2828
}

opentelemetry-otlp/src/exporter/http/metrics.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,16 @@ impl MetricsClient for OtlpHttpClient {
1919
_ => Err(OTelSdkError::AlreadyShutdown),
2020
})?;
2121

22-
let (body, content_type, content_encoding) = self.build_metrics_export_body(metrics).ok_or_else(|| {
23-
OTelSdkError::InternalFailure("Failed to serialize metrics".to_string())
24-
})?;
25-
22+
let (body, content_type, content_encoding) =
23+
self.build_metrics_export_body(metrics).ok_or_else(|| {
24+
OTelSdkError::InternalFailure("Failed to serialize metrics".to_string())
25+
})?;
26+
2627
let mut request_builder = http::Request::builder()
2728
.method(Method::POST)
2829
.uri(&self.collector_endpoint)
2930
.header(CONTENT_TYPE, content_type);
30-
31+
3132
if let Some(encoding) = content_encoding {
3233
request_builder = request_builder.header("Content-Encoding", encoding);
3334
}

opentelemetry-otlp/src/exporter/http/mod.rs

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,8 @@ impl HttpExporterBuilder {
213213
#[cfg(feature = "trace")]
214214
pub fn build_span_exporter(mut self) -> Result<crate::SpanExporter, ExporterBuildError> {
215215
use crate::{
216-
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_HEADERS,
217-
OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION,
216+
OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
217+
OTEL_EXPORTER_OTLP_TRACES_HEADERS, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
218218
};
219219

220220
let client = self.build_client(
@@ -232,8 +232,8 @@ impl HttpExporterBuilder {
232232
#[cfg(feature = "logs")]
233233
pub fn build_log_exporter(mut self) -> Result<crate::LogExporter, ExporterBuildError> {
234234
use crate::{
235-
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_LOGS_HEADERS,
236-
OTEL_EXPORTER_OTLP_LOGS_TIMEOUT, OTEL_EXPORTER_OTLP_LOGS_COMPRESSION,
235+
OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_LOGS_ENDPOINT,
236+
OTEL_EXPORTER_OTLP_LOGS_HEADERS, OTEL_EXPORTER_OTLP_LOGS_TIMEOUT,
237237
};
238238

239239
let client = self.build_client(
@@ -254,8 +254,8 @@ impl HttpExporterBuilder {
254254
temporality: opentelemetry_sdk::metrics::Temporality,
255255
) -> Result<crate::MetricExporter, ExporterBuildError> {
256256
use crate::{
257-
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_HEADERS,
258-
OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION,
257+
OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_ENDPOINT,
258+
OTEL_EXPORTER_OTLP_METRICS_HEADERS, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT,
259259
};
260260

261261
let client = self.build_client(
@@ -289,9 +289,9 @@ impl OtlpHttpClient {
289289
match self.compression {
290290
#[cfg(feature = "gzip-http")]
291291
Some(crate::Compression::Gzip) => {
292-
use std::io::Write;
293292
use flate2::{write::GzEncoder, Compression};
294-
293+
use std::io::Write;
294+
295295
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
296296
encoder.write_all(&body).map_err(|e| e.to_string())?;
297297
let compressed = encoder.finish().map_err(|e| e.to_string())?;
@@ -351,7 +351,7 @@ impl OtlpHttpClient {
351351
},
352352
_ => (req.encode_to_vec(), "application/x-protobuf"),
353353
};
354-
354+
355355
let (compressed_body, content_encoding) = self.compress_body(body)?;
356356
Ok((compressed_body, content_type, content_encoding))
357357
}
@@ -373,7 +373,7 @@ impl OtlpHttpClient {
373373
},
374374
_ => (req.encode_to_vec(), "application/x-protobuf"),
375375
};
376-
376+
377377
let (compressed_body, content_encoding) = self.compress_body(body)?;
378378
Ok((compressed_body, content_type, content_encoding))
379379
}
@@ -398,9 +398,11 @@ impl OtlpHttpClient {
398398
},
399399
_ => (req.encode_to_vec(), "application/x-protobuf"),
400400
};
401-
401+
402402
match self.compress_body(body) {
403-
Ok((compressed_body, content_encoding)) => Some((compressed_body, content_type, content_encoding)),
403+
Ok((compressed_body, content_encoding)) => {
404+
Some((compressed_body, content_type, content_encoding))
405+
}
404406
Err(e) => {
405407
otel_debug!(name: "CompressionFailed", error = e);
406408
None
@@ -821,8 +823,8 @@ mod tests {
821823
mod compression_tests {
822824
use super::super::OtlpHttpClient;
823825
use flate2::read::GzDecoder;
826+
use opentelemetry_http::{Bytes, HttpClient};
824827
use std::io::Read;
825-
use opentelemetry_http::{HttpClient, Bytes};
826828

827829
#[test]
828830
fn test_gzip_compression_and_decompression() {
@@ -847,7 +849,7 @@ mod tests {
847849
let mut decoder = GzDecoder::new(&compressed_body[..]);
848850
let mut decompressed = Vec::new();
849851
decoder.read_to_end(&mut decompressed).unwrap();
850-
852+
851853
// Verify decompressed data matches original
852854
assert_eq!(decompressed, test_data);
853855
// Verify compression actually happened (compressed should be different)
@@ -876,7 +878,7 @@ mod tests {
876878

877879
// Verify we can decompress the body
878880
let decompressed = zstd::bulk::decompress(&compressed_body, test_data.len()).unwrap();
879-
881+
880882
// Verify decompressed data matches original
881883
assert_eq!(decompressed, test_data);
882884
// Verify compression actually happened (compressed should be different)
@@ -917,10 +919,12 @@ mod tests {
917919

918920
let body = vec![1, 2, 3, 4];
919921
let result = client.compress_body(body);
920-
922+
921923
// Should return error when gzip requested but feature not enabled
922924
assert!(result.is_err());
923-
assert!(result.unwrap_err().contains("gzip-http feature not enabled"));
925+
assert!(result
926+
.unwrap_err()
927+
.contains("gzip-http feature not enabled"));
924928
}
925929

926930
#[cfg(not(feature = "zstd-http"))]
@@ -937,10 +941,12 @@ mod tests {
937941

938942
let body = vec![1, 2, 3, 4];
939943
let result = client.compress_body(body);
940-
944+
941945
// Should return error when zstd requested but feature not enabled
942946
assert!(result.is_err());
943-
assert!(result.unwrap_err().contains("zstd-http feature not enabled"));
947+
assert!(result
948+
.unwrap_err()
949+
.contains("zstd-http feature not enabled"));
944950
}
945951

946952
// Mock HTTP client for testing

opentelemetry-otlp/src/exporter/http/trace.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl SpanExporter for OtlpHttpClient {
3131
.method(Method::POST)
3232
.uri(&self.collector_endpoint)
3333
.header(CONTENT_TYPE, content_type);
34-
34+
3535
if let Some(encoding) = content_encoding {
3636
request_builder = request_builder.header("Content-Encoding", encoding);
3737
}

opentelemetry-otlp/src/exporter/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,11 +171,11 @@ impl FromStr for Compression {
171171

172172
/// Resolve compression from environment variables with priority:
173173
/// 1. Provided config value
174-
/// 2. Signal-specific environment variable
174+
/// 2. Signal-specific environment variable
175175
/// 3. Generic OTEL_EXPORTER_OTLP_COMPRESSION
176176
/// 4. None (default)
177177
fn resolve_compression_from_env(
178-
config_compression: Option<Compression>,
178+
config_compression: Option<Compression>,
179179
signal_env_var: &str,
180180
) -> Result<Option<Compression>, ExporterBuildError> {
181181
if let Some(compression) = config_compression {

opentelemetry-otlp/src/exporter/tonic/mod.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ use tonic::transport::ClientTlsConfig;
1414
use super::{default_headers, parse_header_string, OTEL_EXPORTER_OTLP_GRPC_ENDPOINT_DEFAULT};
1515
use super::{resolve_timeout, ExporterBuildError};
1616
use crate::exporter::Compression;
17-
use crate::{
18-
ExportConfig, OTEL_EXPORTER_OTLP_ENDPOINT,
19-
OTEL_EXPORTER_OTLP_HEADERS,
20-
};
17+
use crate::{ExportConfig, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS};
2118

2219
#[cfg(feature = "logs")]
2320
pub(crate) mod logs;

0 commit comments

Comments
 (0)