Stamp OTLP log records with their observed time
Browse files at this commit382bfca482d988b0ffb3c4a25174a63b8c1d28b5Parent: 1ab3b60- fix
- stamp OTLP log records with their observed time
1 changed file +62 -2
- src/telemetry.rs +62 -2
src/telemetry.rsmodified+62 -2
| @@ -19,7 +19,7 @@ use std::sync::{Arc, OnceLock}; | |||
| 19 | use opentelemetry::metrics::{Counter, Gauge, Histogram, UpDownCounter}; | 19 | use opentelemetry::metrics::{Counter, Gauge, Histogram, UpDownCounter}; |
| 20 | use opentelemetry::{KeyValue, global}; | 20 | use opentelemetry::{KeyValue, global}; |
| 21 | use opentelemetry_sdk::Resource; | 21 | use opentelemetry_sdk::Resource; |
| 22 | -use opentelemetry_sdk::logs::SdkLoggerProvider; | 22 | +use opentelemetry_sdk::logs::{LogProcessor, SdkLogRecord, SdkLoggerProvider}; |
| 23 | use opentelemetry_sdk::metrics::SdkMeterProvider; | 23 | use opentelemetry_sdk::metrics::SdkMeterProvider; |
| 24 | use opentelemetry_sdk::trace::SdkTracerProvider; | 24 | use opentelemetry_sdk::trace::SdkTracerProvider; |
| 25 | use tracing_subscriber::layer::SubscriberExt; | 25 | use tracing_subscriber::layer::SubscriberExt; |
| @@ -365,6 +365,9 @@ pub fn init(cfg: &TelemetryConfig) -> Result<(TelemetryGuard, Metrics), Telemetr | |||
| 365 | .build(); | 365 | .build(); |
| 366 | let logger_provider = SdkLoggerProvider::builder() | 366 | let logger_provider = SdkLoggerProvider::builder() |
| 367 | .with_resource(resource) | 367 | .with_resource(resource) |
| 368 | + // Registered before the exporter: processors run in registration order, | ||
| 369 | + // so the stamp lands before the batch processor clones the record. | ||
| 370 | + .with_log_processor(StampTimestamp) | ||
| 368 | .with_batch_exporter(protocol.log_exporter()?) | 371 | .with_batch_exporter(protocol.log_exporter()?) |
| 369 | .build(); | 372 | .build(); |
| 370 | 373 | ||
| @@ -398,6 +401,37 @@ pub fn init(cfg: &TelemetryConfig) -> Result<(TelemetryGuard, Metrics), Telemetr | |||
| 398 | )) | 401 | )) |
| 399 | } | 402 | } |
| 400 | 403 | ||
| 404 | +/// Gives every log record the `timestamp` the appender never sets. | ||
| 405 | +/// | ||
| 406 | +/// `opentelemetry-appender-tracing` 0.32 leaves `timestamp` empty and the SDK | ||
| 407 | +/// fills only `observed_timestamp`, so collectors render the event as | ||
| 408 | +/// 1970-01-01 and anything ordering on `timestamp` sorts it first forever. The | ||
| 409 | +/// two differ only by the queueing delay inside this process, so copying the | ||
| 410 | +/// observed time across is the honest value. No clock is read here — that would | ||
| 411 | +/// invent a time the record does not have (and `SystemTime::now` is banned; see | ||
| 412 | +/// clippy.toml). | ||
| 413 | +#[derive(Debug)] | ||
| 414 | +struct StampTimestamp; | ||
| 415 | + | ||
| 416 | +impl LogProcessor for StampTimestamp { | ||
| 417 | + fn emit(&self, data: &mut SdkLogRecord, _scope: &opentelemetry::InstrumentationScope) { | ||
| 418 | + use opentelemetry::logs::LogRecord as _; | ||
| 419 | + if data.timestamp().is_none() | ||
| 420 | + && let Some(observed) = data.observed_timestamp() | ||
| 421 | + { | ||
| 422 | + data.set_timestamp(observed); | ||
| 423 | + } | ||
| 424 | + } | ||
| 425 | + | ||
| 426 | + fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult { | ||
| 427 | + Ok(()) | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + fn shutdown(&self) -> opentelemetry_sdk::error::OTelSdkResult { | ||
| 431 | + Ok(()) | ||
| 432 | + } | ||
| 433 | +} | ||
| 434 | + | ||
| 401 | /// Hand the instruments to [`Metrics::global`]. A second [`init`] (there is | 435 | /// Hand the instruments to [`Metrics::global`]. A second [`init`] (there is |
| 402 | /// none in production) keeps the first set rather than swapping under callers. | 436 | /// none in production) keeps the first set rather than swapping under callers. |
| 403 | fn publish(metrics: Metrics) -> Metrics { | 437 | fn publish(metrics: Metrics) -> Metrics { |
| @@ -517,7 +551,10 @@ fn resource() -> Resource { | |||
| 517 | 551 | ||
| 518 | #[cfg(test)] | 552 | #[cfg(test)] |
| 519 | mod tests { | 553 | mod tests { |
| 520 | - use super::{LogFormat, TelemetryError}; | 554 | + use opentelemetry::logs::{LogRecord as _, Logger as _, LoggerProvider as _}; |
| 555 | + use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider}; | ||
| 556 | + | ||
| 557 | + use super::{LogFormat, StampTimestamp, TelemetryError}; | ||
| 521 | 558 | ||
| 522 | #[tokio::test] | 559 | #[tokio::test] |
| 523 | async fn log_format_parses_the_two_spellings_and_rejects_the_rest() { | 560 | async fn log_format_parses_the_two_spellings_and_rejects_the_rest() { |
| @@ -539,4 +576,27 @@ mod tests { | |||
| 539 | let err = LogFormat::parse(Some("logfmt".into())).unwrap_err(); | 576 | let err = LogFormat::parse(Some("logfmt".into())).unwrap_err(); |
| 540 | assert!(matches!(err, TelemetryError::LogFormat(v) if v == "logfmt")); | 577 | assert!(matches!(err, TelemetryError::LogFormat(v) if v == "logfmt")); |
| 541 | } | 578 | } |
| 579 | + | ||
| 580 | + #[tokio::test] | ||
| 581 | + async fn a_record_without_a_timestamp_is_stamped_with_its_observed_time() { | ||
| 582 | + let exporter = InMemoryLogExporter::default(); | ||
| 583 | + let provider = SdkLoggerProvider::builder() | ||
| 584 | + .with_log_processor(StampTimestamp) | ||
| 585 | + .with_simple_exporter(exporter.clone()) | ||
| 586 | + .build(); | ||
| 587 | + let logger = provider.logger("test"); | ||
| 588 | + | ||
| 589 | + // What the tracing appender hands the SDK: no `timestamp` at all. | ||
| 590 | + let mut record = logger.create_log_record(); | ||
| 591 | + record.set_body("hello".into()); | ||
| 592 | + logger.emit(record); | ||
| 593 | + provider.force_flush().unwrap(); | ||
| 594 | + | ||
| 595 | + let logs = exporter.get_emitted_logs().unwrap(); | ||
| 596 | + assert_eq!(logs.len(), 1); | ||
| 597 | + let exported = &logs[0].record; | ||
| 598 | + // Not 1970, and not a freshly invented clock read either. | ||
| 599 | + assert!(exported.timestamp().is_some()); | ||
| 600 | + assert_eq!(exported.timestamp(), exported.observed_timestamp()); | ||
| 601 | + } | ||
| 542 | } | 602 | } |