tracing_perfetto_file/lib.rs
1// Copyright 2026 Lalit Maganti
2// SPDX-License-Identifier: Apache-2.0
3
4#![doc = include_str!("../README.md")]
5#![deny(missing_docs)]
6
7mod emit;
8mod platform;
9mod proto;
10mod runtime;
11mod sequence;
12mod span_state;
13mod subscriber;
14mod thread;
15mod visitor;
16
17use std::io::Write;
18use std::sync::Arc;
19
20use crate::runtime::{Config, Inner};
21
22/// A [`tracing_subscriber::Layer`] that writes a Perfetto trace stream.
23///
24/// Construct with [`PerfettoLayer::builder`]; see the crate docs for usage.
25#[must_use = "the layer must be installed on a tracing subscriber"]
26pub struct PerfettoLayer {
27 inner: Arc<Inner>,
28}
29
30impl PerfettoLayer {
31 /// Starts building a layer that writes the trace to `writer`.
32 ///
33 /// The writer may be any owned [`Write`] sink, not just a file. For
34 /// example, a TCP connection can stream trace data to a collector:
35 ///
36 /// ```no_run
37 /// # use tracing_perfetto_file::PerfettoLayer;
38 /// let stream = std::net::TcpStream::connect("127.0.0.1:9001")?;
39 /// let (layer, guard) = PerfettoLayer::builder(stream).build();
40 /// # let _ = (layer, guard);
41 /// # Ok::<(), std::io::Error>(())
42 /// ```
43 ///
44 /// Slices, instants, flows, poll linking, levels, and targets are always
45 /// on. Additional data is opt-in through the builder's `with_*` methods.
46 pub fn builder(writer: impl Write + Send + 'static) -> PerfettoLayerBuilder {
47 PerfettoLayerBuilder {
48 writer: Box::new(writer),
49 config: Config {
50 span_mode: SpanMode::default(),
51 debug_annotations: false,
52 poll_slices: false,
53 source_locations: false,
54 counters: false,
55 },
56 }
57 }
58}
59
60/// Configures and builds a [`PerfettoLayer`].
61#[must_use = "the builder does nothing until build is called"]
62pub struct PerfettoLayerBuilder {
63 writer: Box<dyn Write + Send>,
64 config: Config,
65}
66
67impl PerfettoLayerBuilder {
68 /// Selects how spans map onto tracks. Default: [`SpanMode::SpanTracks`].
69 pub fn span_mode(mut self, mode: SpanMode) -> Self {
70 self.config.span_mode = mode;
71 self
72 }
73
74 /// Records span and event fields as Perfetto debug annotations, visible
75 /// when selecting a slice in the UI.
76 pub fn with_debug_annotations(mut self) -> Self {
77 self.config.debug_annotations = true;
78 self
79 }
80
81 /// SpanTracks only: emits a nested `poll` slice per enter->exit interval
82 /// inside each span's lifetime slice.
83 pub fn with_poll_slices(mut self) -> Self {
84 self.config.poll_slices = true;
85 self
86 }
87
88 /// Records each span's and event's file and line as a Perfetto source
89 /// location.
90 pub fn with_source_locations(mut self) -> Self {
91 self.config.source_locations = true;
92 self
93 }
94
95 /// Maps numeric event fields named `counter.*` to Perfetto counter
96 /// tracks instead of debug annotations, e.g.
97 /// `tracing::info!(counter.queue_depth = 42)` plots `queue_depth` as a
98 /// per-process counter.
99 pub fn with_counters(mut self) -> Self {
100 self.config.counters = true;
101 self
102 }
103
104 /// Builds the layer. Keep the returned [`FlushGuard`] alive for the
105 /// duration of tracing; dropping it flushes all buffered data.
106 pub fn build(self) -> (PerfettoLayer, FlushGuard) {
107 let inner = Arc::new(Inner::new(self.writer, self.config));
108 (
109 PerfettoLayer {
110 inner: Arc::clone(&inner),
111 },
112 FlushGuard { inner },
113 )
114 }
115}
116
117/// How spans are mapped onto Perfetto tracks.
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum SpanMode {
121 /// Both views at once. Every span gets its own track with a slice covering
122 /// the span's whole lifetime and each enter -> exit interval additionally
123 /// becomes a slice on the thread's track.
124 Both,
125 /// Only the thread-track view: each enter -> exit interval becomes a slice
126 /// on the entering thread's track. Cheapest; async spans show one slice
127 /// per poll.
128 ThreadTracks,
129 /// The default: a lifetime slice per span, parented on the enclosing
130 /// span's track, optionally with nested `poll` slices per enter -> exit
131 /// interval (see [`PerfettoLayerBuilder::with_poll_slices`]).
132 #[default]
133 SpanTracks,
134}
135
136impl SpanMode {
137 /// Whether enter -> exit intervals are emitted on the thread tracks.
138 fn emit_thread_slices(self) -> bool {
139 matches!(self, SpanMode::ThreadTracks | SpanMode::Both)
140 }
141
142 /// Whether spans get their own track with a lifetime slice.
143 fn emit_span_slices(self) -> bool {
144 matches!(self, SpanMode::SpanTracks | SpanMode::Both)
145 }
146}
147
148/// Flushes buffered trace data when dropped.
149///
150/// Trace bytes accumulate in per-thread queues and only reach the output
151/// writer when a queue fills, a thread exits, or the trace is flushed. Keep
152/// this guard alive for the whole tracing session and drop it (or call
153/// [`FlushGuard::flush`]) before consuming the completed trace output.
154#[must_use = "keep the guard alive for the tracing session so buffered data is flushed"]
155pub struct FlushGuard {
156 inner: Arc<Inner>,
157}
158
159impl FlushGuard {
160 /// Drains all threads' queues to the writer and flushes it.
161 ///
162 /// Also surfaces the first write error hit by background emission, if
163 /// any; once a write error occurs, further trace data is discarded.
164 pub fn flush(&self) -> std::io::Result<()> {
165 self.inner.flush_all()
166 }
167}
168
169impl Drop for FlushGuard {
170 fn drop(&mut self) {
171 let _ = self.inner.flush_all();
172 }
173}