Skip to content

add support for inferring token from region #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2025
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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ thiserror = "2"
serde = { version = "1", features = ["derive"], optional = true }
nu-ansi-term = "0.50.1"
chrono = "0.4.39"
regex = "1.11.1"

[dev-dependencies]
async-trait = "0.1.88"
Expand Down
5 changes: 4 additions & 1 deletion examples/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ static BASIC_COUNTER: LazyLock<Counter<u64>> = LazyLock::new(|| {
});

fn main() -> Result<(), Box<dyn std::error::Error>> {
let shutdown_handler = logfire::configure().install_panic_handler().finish()?;
let shutdown_handler = logfire::configure()
.install_panic_handler()
.with_console(None)
.finish()?;

logfire::info!("Hello, world!");

Expand Down
51 changes: 39 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use opentelemetry_sdk::{
metrics::reader::MetricReader,
trace::{IdGenerator, SpanProcessor},
};
use regex::Regex;

use crate::ConfigureError;

Expand Down Expand Up @@ -168,9 +169,10 @@ impl std::fmt::Debug for Target {
}

/// Options primarily used for testing by Logfire developers.
#[derive(Default)]
pub struct AdvancedOptions {
/// Root URL for the Logfire API.
pub(crate) base_url: String,
pub(crate) base_url: Option<String>,
/// Generator for trace and span IDs.
pub(crate) id_generator: Option<BoxedIdGenerator>,
/// Resource to override default resource detection.
Expand All @@ -186,21 +188,11 @@ pub struct AdvancedOptions {
// pub log_record_processors: Vec<Box<dyn LogRecordProcessor>>,
}

impl Default for AdvancedOptions {
fn default() -> Self {
AdvancedOptions {
base_url: "https://logfire-api.pydantic.dev".to_string(),
id_generator: None,
resource: None,
}
}
}

impl AdvancedOptions {
/// Set the base URL for the Logfire API.
#[must_use]
pub fn with_base_url<T: AsRef<str>>(mut self, base_url: T) -> Self {
self.base_url = base_url.as_ref().into();
self.base_url = Some(base_url.as_ref().into());
self
}

Expand All @@ -222,6 +214,41 @@ impl AdvancedOptions {
}
}

struct RegionData {
base_url: &'static str,
#[expect(dead_code)] // not used for the moment
gcp_region: &'static str,
}

const US_REGION: RegionData = RegionData {
base_url: "https://logfire-us.pydantic.dev",
gcp_region: "us-east4",
};

const EU_REGION: RegionData = RegionData {
base_url: "https://logfire-eu.pydantic.dev",
gcp_region: "europe-west4",
};

/// Get the base API URL from the token's region.
pub(crate) fn get_base_url_from_token(token: &str) -> &'static str {
let pydantic_logfire_token_pattern = Regex::new(
r"^(?P<safe_part>pylf_v(?P<version>[0-9]+)_(?P<region>[a-z]+)_)(?P<token>[a-zA-Z0-9]+)$",
)
.expect("token regex is known to be valid");

#[expect(clippy::wildcard_in_or_patterns, reason = "being explicit about us")]
match pydantic_logfire_token_pattern
.captures(token)
.and_then(|captures| captures.name("region"))
.map(|region| region.as_str())
{
Some("eu") => EU_REGION.base_url,
// fallback to US region if the token / region is not recognized
Some("us") | _ => US_REGION.base_url,
}
}

/// Configuration of metrics.
///
/// This only has one option for now, but it's a place to add more related options in the future.
Expand Down
33 changes: 24 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ use std::sync::{Arc, Once};
use std::{backtrace::Backtrace, env::VarError, sync::OnceLock, time::Duration};

use bridges::tracing::LogfireTracingPendingSpanNotSentLayer;
use config::get_base_url_from_token;
use opentelemetry::trace::TracerProvider;
use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider};
use opentelemetry_sdk::trace::{
Expand Down Expand Up @@ -501,17 +502,29 @@ impl LogfireConfigBuilder {

let mut http_headers: Option<HashMap<String, String>> = None;

if send_to_logfire {
let logfire_base_url = if send_to_logfire {
let Some(token) = token else {
return Err(ConfigureError::TokenRequired);
};

http_headers
.get_or_insert_default()
.insert("Authorization".to_string(), format!("Bearer {token}"));

Some(
advanced_options
.base_url
.as_deref()
.unwrap_or_else(|| get_base_url_from_token(&token)),
)
} else {
None
};

if let Some(logfire_base_url) = logfire_base_url {
tracer_provider_builder = tracer_provider_builder.with_span_processor(
BatchSpanProcessor::builder(exporters::span_exporter(
&advanced_options.base_url,
logfire_base_url,
http_headers.clone(),
)?)
.with_batch_config(
Expand Down Expand Up @@ -570,14 +583,16 @@ impl LogfireConfigBuilder {

let mut meter_provider_builder = SdkMeterProvider::builder();

if send_to_logfire && self.enable_metrics {
let metric_reader = PeriodicReader::builder(exporters::metric_exporter(
&advanced_options.base_url,
http_headers,
)?)
.build();
if let Some(logfire_base_url) = logfire_base_url {
if self.enable_metrics {
let metric_reader = PeriodicReader::builder(exporters::metric_exporter(
logfire_base_url,
http_headers,
)?)
.build();

meter_provider_builder = meter_provider_builder.with_reader(metric_reader);
meter_provider_builder = meter_provider_builder.with_reader(metric_reader);
}
};

if let Some(metrics) = self.metrics.filter(|_| self.enable_metrics) {
Expand Down
2 changes: 1 addition & 1 deletion tests/test_basic_exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1032,7 +1032,7 @@ fn test_basic_span() {
"code.lineno",
),
value: I64(
675,
690,
),
},
KeyValue {
Expand Down