Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5c42302
feat: add opentelemetry-otlp-file crate implementing the OTLP File Ex…
garysassano Sep 28, 2026
eab4861
docs: link the changelog entry to its pull request
garysassano Sep 28, 2026
e430738
test: use span timestamps that SystemTime can represent on Windows
garysassano Sep 28, 2026
b91b3e4
Merge branch 'main' into feat/otlp-file-exporter
garysassano Sep 30, 2026
5c40464
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 2, 2026
109c157
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 5, 2026
aec4ec7
chore(otlp-file): align keywords and drop non_exhaustive on ExporterB…
garysassano Oct 6, 2026
a4235c2
docs(otlp-file): compare flushing strategies on AWS Lambda
garysassano Oct 6, 2026
dbaf1b4
fix(otlp-file): complete a partly written line before writing the nex…
garysassano Oct 9, 2026
4b41ca8
docs(otlp-file): document the receiver line limit and blocking writes
garysassano Oct 9, 2026
1f1c35f
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 9, 2026
4733c95
chore(otlp-file): align version with the 0.33.1 workspace release
garysassano Oct 9, 2026
e8bf3b7
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 11, 2026
d101c17
refactor(otlp-file): rename Output to OutputStream
garysassano Oct 22, 2026
02f053d
refactor(otlp-file): consolidate the output stream types
garysassano Oct 22, 2026
003a6ff
feat(otlp-file): sync files to disk on force_flush and shutdown
garysassano Oct 22, 2026
5cb896a
test(otlp-file): export each signal through the SDK to a real file
garysassano Oct 22, 2026
9fd33e2
test(otlp-file): pin the metric tests to an explicit reader interval
garysassano Oct 22, 2026
9099bf6
chore: publish opentelemetry-otlp-file
garysassano Oct 22, 2026
06c305a
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 22, 2026
d219b40
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 28, 2026
450bf90
Merge branch 'main' into feat/otlp-file-exporter
garysassano Oct 29, 2026
e78e9a6
Merge branch 'main' into feat/otlp-file-exporter
garysassano Nov 8, 2026
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ jobs:
external-types:
strategy:
matrix:
member: [opentelemetry, opentelemetry-sdk, opentelemetry-http, opentelemetry-otlp, opentelemetry-propagator-b3]
member: [opentelemetry, opentelemetry-sdk, opentelemetry-http, opentelemetry-otlp, opentelemetry-otlp-file, opentelemetry-propagator-b3]
runs-on: ubuntu-latest # TODO: Check if this could be covered for Windows. The step used currently fails on Windows.
steps:
- name: Harden the runner (Audit all outbound calls)
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ The following crates are maintained in this repo:
or [vendor specific endpoints](https://opentelemetry.io/ecosystem/vendors/).
* [`opentelemetry-stdout`] exporter for sending logs, metrics and traces to
stdout, for learning/debugging purposes.
* [`opentelemetry-otlp-file`](./opentelemetry-otlp-file) exporter that writes logs, metrics and traces as OTLP JSON lines to stdout or a file, as described by the [OTLP File Exporter](https://opentelemetry.io/docs/specs/otel/protocol/file-exporter/) specification.
* [`opentelemetry-http`] This crate contains utility functions to help with
exporting telemetry, propagation, over [`http`].
* [`opentelemetry-appender-log`] This crate provides logging appender to route
Expand Down
5 changes: 5 additions & 0 deletions opentelemetry-otlp-file/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## vNext

- Initial release. `SpanExporter`, `MetricExporter` and `LogExporter` write traces, metrics and logs as OTLP JSON lines to stdout, to a file, or to any `std::io::Write` implementation, as described by the [OpenTelemetry Protocol File Exporter](https://opentelemetry.io/docs/specs/otel/protocol/file-exporter/) specification. [#3763](https://github.com/open-telemetry/opentelemetry-rust/pull/3763)
53 changes: 53 additions & 0 deletions opentelemetry-otlp-file/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
[package]
Comment thread
garysassano marked this conversation as resolved.
Resolved
name = "opentelemetry-otlp-file"
version = "0.33.1"
description = "OpenTelemetry Protocol File Exporter: writes OTLP JSON Lines to stdout or a file"
homepage = "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-otlp-file"
repository = "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-otlp-file"
readme = "README.md"
categories = [
"development-tools::debugging",
"development-tools::profiling",
]
keywords = ["opentelemetry", "otlp", "logging", "tracing", "metrics"]
license = "Apache-2.0"
edition = "2021"
rust-version = "1.75.0"
autobenches = false

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[dependencies]
opentelemetry = { workspace = true, default-features = false }
opentelemetry_sdk = { workspace = true, default-features = false }
opentelemetry-proto = { workspace = true, default-features = false, features = ["gen-tonic-messages", "with-serde"] }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }

[dev-dependencies]
futures-executor = { workspace = true }
opentelemetry-appender-tracing = { workspace = true }
tempfile = { workspace = true }
temp-env = { workspace = true }
tracing = { workspace = true, features = ["std"] }
tracing-subscriber = { workspace = true, features = ["registry", "std"] }

[features]
default = ["trace", "metrics", "logs", "internal-logs"]
trace = ["opentelemetry/trace", "opentelemetry_sdk/trace", "opentelemetry-proto/trace"]
metrics = ["opentelemetry/metrics", "opentelemetry_sdk/metrics", "opentelemetry-proto/metrics"]
logs = ["opentelemetry/logs", "opentelemetry_sdk/logs", "opentelemetry-proto/logs"]
internal-logs = ["opentelemetry/internal-logs", "opentelemetry_sdk/internal-logs"]

[[example]]
name = "basic"
required-features = ["trace", "metrics", "logs"]

[lints]
workspace = true

[lib]
bench = false
125 changes: 125 additions & 0 deletions opentelemetry-otlp-file/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# OpenTelemetry Protocol File Exporter

![OpenTelemetry — An observability framework for cloud-native software.][splash]

[splash]: https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo-text.png

This crate contains [OpenTelemetry](https://opentelemetry.io/) exporters that write traces, metrics and logs as [OTLP JSON](https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding) lines to stdout, to a file, or to any `std::io::Write` implementation. It implements the [OpenTelemetry Protocol File Exporter](https://opentelemetry.io/docs/specs/otel/protocol/file-exporter/) specification.

> [!WARNING]
> The OTLP File Exporter specification has [Development](https://opentelemetry.io/docs/specs/otel/document-status/) status, so the configuration API of this crate may change. The output is the stable OTLP JSON encoding.

## When to use it

Use these exporters where sending OTLP over the network is not possible or not wanted:

- Function-as-a-Service platforms, such as AWS Lambda, which capture stdout as the function's log stream.
- Containers whose stdout is already collected by a log scraping pipeline.
- Hosts that persist telemetry to local files for reliability.

To send OTLP to a collector over HTTP or gRPC, use [`opentelemetry-otlp`](../opentelemetry-otlp) instead. For human-readable output while debugging, use [`opentelemetry-stdout`](../opentelemetry-stdout).

## Output format

Every export is written as one [JSON Lines](https://jsonlines.org) entry: a single line of compact, UTF-8 encoded JSON terminated by `\n`. `SpanExporter` writes one `TracesData` object per batch of spans, `MetricExporter` writes one `MetricsData` object per collection, and `LogExporter` writes one `LogsData` object per batch of log records.

For example, a batch with a single span:

```json
{"resourceSpans":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"checkout"}}],"droppedAttributesCount":0,"entityRefs":[]},"scopeSpans":[{"scope":{"name":"checkout","version":"","attributes":[],"droppedAttributesCount":0},"spans":[{"traceId":"0a079c94ed47f19726c508c68784b1ca","spanId":"179fe26c0a822afa","traceState":"","parentSpanId":"","flags":257,"name":"GET /cart","kind":2,"startTimeUnixNano":"1790637708114866590","endTimeUnixNano":"1790637708114868607","attributes":[],"droppedAttributesCount":0,"events":[],"droppedEventsCount":0,"links":[],"droppedLinksCount":0,"status":{"message":"","code":0}}],"schemaUrl":""}],"schemaUrl":""}]}
```

Any OTLP JSON consumer can read these lines, for example the OpenTelemetry Collector's [OTLP JSON file receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/otlpjsonfilereceiver). The receiver reads lines of up to 1 MiB by default and splits or truncates longer ones, so the telemetry in such a line is lost; in Collector contrib 0.162.0 this happens without an error at the default log level. Set its `max_log_size` option above the longest line you expect, or keep lines short with smaller batches, for example with `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` for spans and `OTEL_BLRP_MAX_EXPORT_BATCH_SIZE` for log records. A metrics line contains every metric stream of a collection, so its length depends on the number of streams instead.

## Getting started

```rust
use opentelemetry_otlp_file::{MetricExporter, SpanExporter};
use opentelemetry_sdk::metrics::SdkMeterProvider;
use opentelemetry_sdk::trace::SdkTracerProvider;

fn main() -> Result<(), Box<dyn std::error::Error>> {
// Spans are written to stdout, the default output.
let tracer_provider = SdkTracerProvider::builder()
.with_batch_exporter(SpanExporter::default())
.build();

// Metrics are appended to a file, which is created if it does not exist.
let meter_provider = SdkMeterProvider::builder()
.with_periodic_exporter(
MetricExporter::builder()
.with_file("/var/log/otel/metrics.jsonl")
.build()?,
)
.build();

// ... run the instrumented application ...

tracer_provider.shutdown()?;
meter_provider.shutdown()?;
Ok(())
}
```

Log records are exported the same way with `LogExporter`; connect the `SdkLoggerProvider` to your logging library with an appender such as [`opentelemetry-appender-tracing`](../opentelemetry-appender-tracing). The [basic example](./examples/basic.rs) exports all three signals:

```sh
# Write every signal to stdout.
cargo run --example basic
# Append each signal to its own file in /tmp/otel.
cargo run --example basic -- /tmp/otel
```

## Destinations

| Builder method | Destination |
| --- | --- |
| `with_stdout()` | The standard output of the process. This is the default. |
| `with_file(path)` | The file at `path`, created if it does not exist and always appended to. |
| `with_writer(writer)` | Any `std::io::Write + Send + 'static` value. |

Files are opened when the exporter is built, so `build()` reports a missing directory or a permission problem. Each line is written and flushed while the exporter holds its writer, and also Rust's `stdout` lock when writing there, so it is complete as soon as the export returns and is never interleaved with other exports or with other output written through Rust's `stdout`, such as `println!`. If a write fails partway through a line, the export returns an error and the rest of the line is written before the next one, so the following lines stay valid; a line of which nothing was written is dropped. Shutting down an exporter flushes and drops its writer, which closes a file that the exporter opened.

The specification requires a file to contain a single type of telemetry, so give each signal its own file. On stdout, the lines share the stream with anything else the process prints; consumers can tell them apart by their top-level key: `resourceSpans`, `resourceMetrics` or `resourceLogs`.

Exports write with the blocking `std::io::Write` API. The SDK's default batch processors and periodic reader export from their own threads, so a slow destination only delays those threads, whereas `with_simple_exporter` writes on the thread that ends the span or emits the log record, which may be running an async task. The experimental processors and readers that run on an async runtime, enabled by the `experimental_*_with_async_runtime` features of `opentelemetry_sdk`, export on that runtime instead: a slow or blocked write, such as stdout connected to a full pipe, blocks one of its worker threads, and the export timeout cannot take effect until the write returns. Prefer the default processors and reader with these exporters.

## AWS Lambda and other short-lived environments

Lambda sends a function's stdout to CloudWatch Logs, so the exported lines land in the function's log group, from where they can be forwarded, for example with a subscription filter, to anything that reads OTLP JSON.

Batch processors and the periodic reader export from background threads. Lambda freezes the execution environment once the handler has returned and no other event is waiting, and does not notify the function beforehand. While the environment is frozen these threads do not run, so whatever they hold is written after the next invocation thaws it, or is lost if Lambda removes the environment first. Lambda sends `SIGTERM` before removing an environment only when an extension is registered, and then allows 500 ms for the shutdown when all registered extensions are internal. Choose one of these approaches:

- Flush the providers at the end of each invocation. Nothing is left in memory between invocations, at the cost of the time each flush adds to the response. Because the periodic reader exports every metric stream on each flush, the function also writes a metrics line on every invocation, however often it runs.

```rust
tracer_provider.force_flush()?;
meter_provider.force_flush()?;
logger_provider.force_flush()?;
```

- Leave the batch processors and the periodic reader to export on their own schedule, and flush when the environment shuts down, for example from the hook passed to [`lambda_runtime::spawn_graceful_shutdown_handler`](https://docs.rs/lambda_runtime/latest/lambda_runtime/fn.spawn_graceful_shutdown_handler.html), which registers an extension so that the function receives `SIGTERM`. This writes the fewest lines under steady traffic, but telemetry can wait in memory until the next invocation, and is lost if the environment is reset after a timeout or crash.
- Flush from an [internal extension](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html) registered for `INVOKE` events once the handler has returned. Lambda sends the response without waiting for extensions, so the flush does not delay it, although its duration is still billed.

`with_simple_exporter` writes each span or log record as soon as it ends, so nothing waits in memory, but every record becomes its own line that repeats the resource, which increases the number of CloudWatch log events and the bytes ingested.

With the `provided.al2023` runtime, every exported line becomes one CloudWatch log event, whether the function uses the Text or the JSON log format. A line longer than about 256 KiB, the CloudWatch Logs event size limit, is split across consecutive log events, and only the last part ends with a newline, so a consumer has to join the parts back together. Keep batches small to avoid this, for example with `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` for spans and `OTEL_BLRP_MAX_EXPORT_BATCH_SIZE` for log records.

## Configuration

The Rust SDK does not select exporters from the `OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER` and `OTEL_LOGS_EXPORTER` environment variables, so these exporters are configured in code.

`MetricExporter` reads `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`, which accepts `cumulative` (the default), `delta` or `lowmemory`. `MetricExporterBuilder::with_temporality` takes precedence over it. `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION` is not supported, because the SDK does not let exporters choose the default aggregation; use a view to select the histogram aggregation instead.

## Feature flags

- `trace`: the span exporter. Enabled by default.
- `metrics`: the metric exporter. Enabled by default.
- `logs`: the log exporter. Enabled by default.
- `internal-logs`: report problems, such as an invalid environment variable, through the OpenTelemetry internal logging macros. Enabled by default.

## Supported Rust Versions

OpenTelemetry is built against the latest stable release. The minimum supported version is 1.75.0. The current OpenTelemetry version is NOT guaranteed to build on Rust versions earlier than the minimum supported version.

The current stable Rust compiler and the three most recent minor versions before it will always be supported. For example, if the current stable compiler version is 1.49, the minimum supported version will not be increased past 1.46, three minor versions prior. Increasing the minimum supported compiler version is not considered a semver breaking change as long as doing so complies with this policy.
11 changes: 11 additions & 0 deletions opentelemetry-otlp-file/allowed-external-types.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0
# This is used with cargo-check-external-types to reduce the surface area of downstream crates from
# the public API. Ideally this can have a few exceptions as possible.
allowed_external_types = [
# opentelemetry-sdk
"opentelemetry_sdk::logs::export::LogExporter",
"opentelemetry_sdk::metrics::exporter::PushMetricExporter",
"opentelemetry_sdk::metrics::Temporality",
"opentelemetry_sdk::trace::export::SpanExporter",
]
94 changes: 94 additions & 0 deletions opentelemetry-otlp-file/examples/basic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Writes traces, metrics and logs as OTLP JSON lines.
//!
//! Write every signal to stdout:
//!
//! ```shell
//! cargo run --example basic
//! ```
//!
//! Or append each signal to its own file in a directory:
//!
//! ```shell
//! cargo run --example basic -- /tmp/otel
//! ```
//!
//! This creates `traces.jsonl`, `metrics.jsonl` and `logs.jsonl` in `/tmp/otel`.

use std::error::Error;
use std::path::Path;

use opentelemetry::metrics::MeterProvider as _;
use opentelemetry::trace::{TraceContextExt as _, Tracer as _, TracerProvider as _};
use opentelemetry::KeyValue;
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp_file::{LogExporter, MetricExporter, SpanExporter};
use opentelemetry_sdk::logs::SdkLoggerProvider;
use opentelemetry_sdk::metrics::SdkMeterProvider;
use opentelemetry_sdk::trace::SdkTracerProvider;
use opentelemetry_sdk::Resource;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::prelude::*;

fn main() -> Result<(), Box<dyn Error>> {
let (span_exporter, metric_exporter, log_exporter) = match std::env::args().nth(1) {
Some(dir) => {
let dir = Path::new(&dir);
(
SpanExporter::builder()
.with_file(dir.join("traces.jsonl"))
.build()?,
MetricExporter::builder()
.with_file(dir.join("metrics.jsonl"))
.build()?,
LogExporter::builder()
.with_file(dir.join("logs.jsonl"))
.build()?,
)
}
None => (
SpanExporter::default(),
MetricExporter::default(),
LogExporter::default(),
),
};

let resource = Resource::builder()
.with_service_name("otlp-file-example")
.build();
let tracer_provider = SdkTracerProvider::builder()
.with_resource(resource.clone())
.with_batch_exporter(span_exporter)
.build();
let meter_provider = SdkMeterProvider::builder()
.with_resource(resource.clone())
.with_periodic_exporter(metric_exporter)
.build();
let logger_provider = SdkLoggerProvider::builder()
.with_resource(resource)
.with_batch_exporter(log_exporter)
.build();
// Export `info` and above, which leaves out the SDK's own debug logs.
tracing_subscriber::registry()
.with(OpenTelemetryTracingBridge::new(&logger_provider).with_filter(LevelFilter::INFO))
.init();

let tracer = tracer_provider.tracer("otlp-file-example");
let orders = meter_provider
.meter("otlp-file-example")
.u64_counter("orders")
.build();

tracer.in_span("checkout", |cx| {
cx.span()
.set_attribute(KeyValue::new("payment.method", "card"));
tracer.in_span("charge card", |_| {});
orders.add(1, &[KeyValue::new("payment.method", "card")]);
tracing::info!(name: "order.placed", order_id = 42, "order placed");
});

// Shutting down exports everything that is still buffered.
tracer_provider.shutdown()?;
meter_provider.shutdown()?;
logger_provider.shutdown()?;
Ok(())
}
15 changes: 15 additions & 0 deletions opentelemetry-otlp-file/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::io;
use std::path::PathBuf;

/// Errors that can occur while building an exporter.
#[derive(Debug, thiserror::Error)]
pub enum ExporterBuildError {
/// The file configured as the output could not be opened for appending.
#[error("failed to open {} for appending: {source}", .path.display())]
OpenFile {
/// The configured file path.
path: PathBuf,
/// The error reported by the operating system.
source: io::Error,
},
}
Loading
Loading