Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- Add `span_exporter()` helper to build a span exporter directly in [#20](https://github.com/pydantic/logfire-rust/pull/20)
- Fix `set_resource` not being called on span processors added with `with_additional_span_processor()` in [#20](https://github.com/pydantic/logfire-rust/pull/20)
- Add `MetricsOptions` for configuring additional metrics exporters in [#21](https://github.com/pydantic/logfire-rust/pull/21)

## [v0.1.0] (2025-03-13)

Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ nu-ansi-term = "0.50.1"
chrono = "0.4.39"

[dev-dependencies]
async-trait = "0.1.88"
insta = "1.42.1"
opentelemetry_sdk = { version = "0.28", default-features = false, features = ["testing"] }
regex = "1.11.1"
tokio = {version = "1.44.1", features = ["test-util"] }
ulid = "1.2.0"

[features]
Expand Down
50 changes: 28 additions & 22 deletions src/bridges/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,15 @@ mod tests {
use crate::{
config::{AdvancedOptions, ConsoleOptions, Target},
set_local_logfire,
tests::{DeterministicExporter, DeterministicIdGenerator},
test_utils::{DeterministicExporter, DeterministicIdGenerator},
};

#[test]
fn test_tracing_bridge() {
let exporter = InMemorySpanExporterBuilder::new().build();

let config = crate::configure()
let handler = crate::configure()
.local()
.send_to_logfire(false)
.with_additional_span_processor(SimpleSpanProcessor::new(Box::new(
DeterministicExporter::new(exporter.clone(), file!(), line!()),
Expand All @@ -249,11 +250,13 @@ mod tests {
.with_default_level_filter(LevelFilter::TRACE)
.with_advanced_options(
AdvancedOptions::default().with_id_generator(DeterministicIdGenerator::new()),
);
)
.finish()
.unwrap();

let guard = set_local_logfire(config).unwrap();
let guard = set_local_logfire(handler);

tracing::subscriber::with_default(guard.subscriber.clone(), || {
tracing::subscriber::with_default(guard.subscriber().clone(), || {
tracing::info!("root event"); // FIXME: this event is not emitted
tracing::info!(name: "root event with value", field_value = 1); // FIXME: this event is not emitted

Expand Down Expand Up @@ -283,7 +286,7 @@ mod tests {
},
parent_span_id: 0000000000000000,
span_kind: Internal,
name: "event src/bridges/tracing.rs:257",
name: "event src/bridges/tracing.rs:260",
start_time: SystemTime {
tv_sec: 0,
tv_nsec: 0,
Expand Down Expand Up @@ -336,7 +339,7 @@ mod tests {
"code.lineno",
),
value: I64(
11,
13,
),
},
KeyValue {
Expand Down Expand Up @@ -444,7 +447,7 @@ mod tests {
"code.lineno",
),
value: I64(
12,
14,
),
},
KeyValue {
Expand Down Expand Up @@ -524,7 +527,7 @@ mod tests {
"code.lineno",
),
value: I64(
14,
16,
),
},
KeyValue {
Expand Down Expand Up @@ -630,7 +633,7 @@ mod tests {
"code.lineno",
),
value: I64(
15,
17,
),
},
KeyValue {
Expand Down Expand Up @@ -746,7 +749,7 @@ mod tests {
"code.lineno",
),
value: I64(
15,
17,
),
},
KeyValue {
Expand Down Expand Up @@ -868,7 +871,7 @@ mod tests {
"code.lineno",
),
value: I64(
16,
18,
),
},
KeyValue {
Expand Down Expand Up @@ -984,7 +987,7 @@ mod tests {
"code.lineno",
),
value: I64(
16,
18,
),
},
KeyValue {
Expand Down Expand Up @@ -1106,7 +1109,7 @@ mod tests {
"code.lineno",
),
value: I64(
17,
19,
),
},
KeyValue {
Expand Down Expand Up @@ -1222,7 +1225,7 @@ mod tests {
"code.lineno",
),
value: I64(
17,
19,
),
},
KeyValue {
Expand Down Expand Up @@ -1344,7 +1347,7 @@ mod tests {
"code.lineno",
),
value: I64(
14,
16,
),
},
KeyValue {
Expand Down Expand Up @@ -1455,7 +1458,7 @@ mod tests {
"code.lineno",
),
value: I64(
265,
268,
),
},
],
Expand Down Expand Up @@ -1521,7 +1524,7 @@ mod tests {
"code.lineno",
),
value: I64(
266,
269,
),
},
],
Expand Down Expand Up @@ -1555,15 +1558,18 @@ mod tests {
..ConsoleOptions::default()
};

let config = crate::configure()
let handler = crate::configure()
.local()
.send_to_logfire(false)
.console_options(console_options.clone())
.install_panic_handler()
.with_default_level_filter(LevelFilter::TRACE);
.with_default_level_filter(LevelFilter::TRACE)
.finish()
.unwrap();

let guard = set_local_logfire(config).unwrap();
let guard = crate::set_local_logfire(handler);

tracing::subscriber::with_default(guard.subscriber.clone(), || {
tracing::subscriber::with_default(guard.subscriber().clone(), || {
tracing::info!("root event");
tracing::info!(name: "root event with value", field_value = 1);

Expand Down
72 changes: 71 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use std::{
sync::{Arc, Mutex},
};

use opentelemetry_sdk::trace::{IdGenerator, SpanProcessor};
use opentelemetry_sdk::{
metrics::reader::MetricReader,
trace::{IdGenerator, SpanProcessor},
};
use tracing::Level;

use crate::ConfigureError;
Expand Down Expand Up @@ -160,6 +163,8 @@ pub struct AdvancedOptions {
pub(crate) base_url: String,
/// Generator for trace and span IDs.
pub(crate) id_generator: Option<BoxedIdGenerator>,
/// Resource to override default resource detection.
pub(crate) resource: Option<opentelemetry_sdk::Resource>,
//
//
// TODO: arguments below supported by Python
Expand All @@ -176,6 +181,7 @@ impl Default for AdvancedOptions {
AdvancedOptions {
base_url: "https://logfire-api.pydantic.dev".to_string(),
id_generator: None,
resource: None,
}
}
}
Expand All @@ -197,6 +203,32 @@ impl AdvancedOptions {
self.id_generator = Some(BoxedIdGenerator::new(Box::new(generator)));
self
}

/// Set the resource; overrides default resource detection.
#[must_use]
pub fn with_resource(mut self, resource: opentelemetry_sdk::Resource) -> Self {
self.resource = Some(resource);
self
}
}

/// Configuration of metrics.
///
/// This only has one option for now, but it's a place to add more related options in the future.
#[derive(Default)]
pub struct MetricsOptions {
/// Sequence of metric readers to be used in addition to the default which exports metrics to Logfire's API.
pub(crate) additional_readers: Vec<BoxedMetricReader>,
}

impl MetricsOptions {
/// Add a metric reader to the list of additional readers.
#[must_use]
pub fn with_additional_reader<T: MetricReader>(mut self, reader: T) -> Self {
self.additional_readers
.push(BoxedMetricReader::new(Box::new(reader)));
self
}
}

/// Wrapper around a `SpanProcessor` to use in `additional_span_processors`.
Expand Down Expand Up @@ -251,6 +283,44 @@ impl IdGenerator for BoxedIdGenerator {
}
}

/// Wrapper around a `MetricReader` to use in `additional_readers`.
#[derive(Debug)]
pub(crate) struct BoxedMetricReader(Box<dyn MetricReader>);

impl BoxedMetricReader {
pub fn new(reader: Box<dyn MetricReader>) -> Self {
BoxedMetricReader(reader)
}
}

impl MetricReader for BoxedMetricReader {
fn register_pipeline(&self, pipeline: std::sync::Weak<opentelemetry_sdk::metrics::Pipeline>) {
self.0.register_pipeline(pipeline);
}

fn collect(
&self,
rm: &mut opentelemetry_sdk::metrics::data::ResourceMetrics,
) -> opentelemetry_sdk::metrics::MetricResult<()> {
self.0.collect(rm)
}

fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
self.0.force_flush()
}

fn shutdown(&self) -> opentelemetry_sdk::error::OTelSdkResult {
self.0.shutdown()
}

fn temporality(
&self,
kind: opentelemetry_sdk::metrics::InstrumentKind,
) -> opentelemetry_sdk::metrics::Temporality {
self.0.temporality(kind)
}
}

#[cfg(test)]
mod tests {
use crate::config::SendToLogfire;
Expand Down
19 changes: 16 additions & 3 deletions src/exporters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ macro_rules! feature_required {
}};
}

/// Build a [`SpanExporter`][opentelemetry::trace::SpanExporter] for passing to
/// Build a [`SpanExporter`][opentelemetry_sdk::trace::SpanExporter] for passing to
/// [`with_additional_span_processor()`][crate::LogfireConfigBuilder::with_additional_span_processor].
///
/// This uses `OTEL_EXPORTER_OTLP_PROTOCOL` and `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` environment
Expand Down Expand Up @@ -98,8 +98,21 @@ pub fn span_exporter(
Ok(RemovePendingSpansExporter::new(span_exporter))
}

// TODO: make this public?
pub(crate) fn metric_exporter(
/// Build a [`PushMetricExporter`][opentelemetry_sdk::metrics::exporter::PushMetricExporter] for passing to
/// [`with_metrics_options()`][crate::LogfireConfigBuilder::with_metrics_options].
///
/// This uses `OTEL_EXPORTER_OTLP_PROTOCOL` and `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` environment
/// variables to determine the protocol to use (or otherwise defaults to [`Protocol::HttpBinary`]).
///
/// # Errors
///
/// Returns an error if the protocol specified by the env var is not supported or if the required feature is not enabled for
/// the given protocol.
///
/// Returns an error if the endpoint is not a valid URI.
///
/// Returns an error if any headers are not valid HTTP headers.
pub fn metric_exporter(
endpoint: &str,
headers: Option<HashMap<String, String>>,
) -> Result<impl PushMetricExporter + use<>, ConfigureError> {
Expand Down
15 changes: 9 additions & 6 deletions src/internal/exporters/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ mod tests {
config::{ConsoleOptions, Target},
internal::exporters::console::{ConsoleWriter, SimpleConsoleSpanExporter},
set_local_logfire,
tests::DeterministicExporter,
test_utils::DeterministicExporter,
};

#[test]
Expand All @@ -279,7 +279,8 @@ mod tests {
..ConsoleOptions::default()
};

let config = crate::configure()
let handler = crate::configure()
.local()
.send_to_logfire(false)
.with_additional_span_processor(SimpleSpanProcessor::new(Box::new(
DeterministicExporter::new(
Expand All @@ -289,12 +290,14 @@ mod tests {
),
)))
.install_panic_handler()
.with_default_level_filter(LevelFilter::TRACE);
.with_default_level_filter(LevelFilter::TRACE)
.finish()
.unwrap();

let guard = set_local_logfire(config).unwrap();
let guard = set_local_logfire(handler);

std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
tracing::subscriber::with_default(guard.subscriber.clone(), || {
tracing::subscriber::with_default(guard.subscriber().clone(), || {
let root = crate::span!("root span").entered();
let _ = crate::span!("hello world span").entered();
let _ = crate::span!(level: Level::DEBUG, "debug span");
Expand All @@ -316,7 +319,7 @@ mod tests {
1970-01-01T00:00:03.000000Z DEBUG logfire::internal::exporters::console::tests debug span
1970-01-01T00:00:05.000000Z DEBUG logfire::internal::exporters::console::tests debug span with explicit parent
1970-01-01T00:00:07.000000Z INFO logfire::internal::exporters::console::tests hello world log
1970-01-01T00:00:08.000000Z ERROR logfire panic: oh no! location=src/internal/exporters/console.rs:303:17, backtrace=disabled backtrace
1970-01-01T00:00:08.000000Z ERROR logfire panic: oh no! location=src/internal/exporters/console.rs:306:17, backtrace=disabled backtrace
"#);
}
}
Loading