Skip to main content

otel/
otel.rs

1use platform_core::{
2    LogFormat, RuntimeSpanAttributes, TelemetryConfig, record_runtime_span_attributes, telemetry,
3};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6#[tokio::main]
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT")
9        .unwrap_or_else(|_| "http://localhost:4317".to_owned());
10    let correlation_id = example_correlation_id();
11
12    telemetry::init(&TelemetryConfig {
13        log_level: "info".to_owned(),
14        log_format: LogFormat::Compact,
15        otlp_endpoint: Some(endpoint),
16    })?;
17
18    emit_outbox_span(&correlation_id);
19    emit_function_span(&correlation_id);
20    telemetry::force_flush()?;
21
22    println!("OTEL_EXAMPLE_CORRELATION_ID={correlation_id}");
23    Ok(())
24}
25
26fn emit_outbox_span(correlation_id: &str) {
27    let span = tracing::info_span!(
28        "outbox_publish",
29        lenso.correlation_id = tracing::field::Empty,
30        lenso.story_id = tracing::field::Empty,
31        lenso.outbox_event_id = tracing::field::Empty,
32        lenso.execution.kind = tracing::field::Empty,
33        lenso.execution.name = tracing::field::Empty,
34    );
35    record_runtime_span_attributes(
36        &span,
37        &RuntimeSpanAttributes::outbox(
38            correlation_id.to_owned(),
39            format!("{correlation_id}:outbox"),
40            "otel_example.runtime_event",
41        ),
42    );
43}
44
45fn emit_function_span(correlation_id: &str) {
46    let span = tracing::info_span!(
47        "function_run",
48        lenso.correlation_id = tracing::field::Empty,
49        lenso.story_id = tracing::field::Empty,
50        lenso.function_run_id = tracing::field::Empty,
51        lenso.execution.kind = tracing::field::Empty,
52        lenso.execution.name = tracing::field::Empty,
53    );
54    record_runtime_span_attributes(
55        &span,
56        &RuntimeSpanAttributes::function(
57            correlation_id.to_owned(),
58            format!("{correlation_id}:function"),
59            "otel_example.runtime_function",
60        ),
61    );
62}
63
64fn example_correlation_id() -> String {
65    let timestamp = SystemTime::now()
66        .duration_since(UNIX_EPOCH)
67        .map(|duration| duration.as_nanos())
68        .unwrap_or_default();
69    format!("otel_example_{timestamp}")
70}