micromegas_tracing/lib.rs
1//! High-performance tracing for logs, metrics, and spans.
2//!
3//! This crate provides low-overhead instrumentation (~20ns per event) for high-performance
4//! applications. Originally designed for video game engines, it focuses on predictable
5//! performance while providing comprehensive observability.
6//!
7//! # Quick Start - Instrumenting Functions
8//!
9//! The easiest way to instrument your code is with the [`#[span_fn]`](prelude::span_fn) attribute macro:
10//!
11//! ```rust,ignore
12//! use micromegas_tracing::prelude::*;
13//!
14//! #[span_fn]
15//! async fn fetch_user(id: u64) -> User {
16//! // Automatically tracks execution time, even across .await points
17//! database.get_user(id).await
18//! }
19//!
20//! #[span_fn]
21//! fn compute_hash(data: &[u8]) -> Hash {
22//! // Works for sync functions too
23//! hasher.hash(data)
24//! }
25//! ```
26//!
27//! [`#[span_fn]`](prelude::span_fn) is the primary tool for instrumenting async code. It correctly tracks
28//! wall-clock time across await points by wrapping the future in an [`InstrumentedFuture`](prelude::InstrumentedFuture).
29//!
30//! # Logging
31//!
32//! ```rust,ignore
33//! use micromegas_tracing::prelude::*;
34//!
35//! info!("User logged in");
36//! warn!("Connection timeout");
37//! error!("Failed to process request");
38//! debug!("Debug info: {value}");
39//! trace!("Detailed trace");
40//! ```
41//!
42//! # Metrics
43//!
44//! ```rust,ignore
45//! use micromegas_tracing::prelude::*;
46//!
47//! imetric!("requests_total", "count", 1);
48//! fmetric!("response_time", "ms", elapsed_ms);
49//! ```
50//!
51//! A name or unit built at run time goes through [`imetric_dyn!`] and [`fmetric_dyn!`], which
52//! copy it into the current block instead of requiring a `'static` string:
53//!
54//! ```rust,ignore
55//! imetric_dyn!(format!("queue.{queue}.depth"), "count", depth);
56//! ```
57//!
58//! # Dynamic properties
59//!
60//! Properties are `key = value` pairs, written before the format string in logs and before the
61//! value in metrics. Keys written in the macros are identifiers or string literals and are always
62//! `'static`. A literal value is interned once per callsite and costs one atomic load afterwards
63//! (unless a `..set` is spread: then the literals before it are copied into the block like dynamic
64//! values, while the spread set's own values are not). Any other value (a correlation, request or
65//! session id) is attached to the individual log entry or measure and copied into the current
66//! block, once per distinct value, and freed with it, so nothing is retained per distinct value:
67//!
68//! ```rust,ignore
69//! use micromegas_tracing::prelude::*;
70//!
71//! let cid = request.correlation_id(); // String
72//! info!(correlation_id = cid, region = "eu", rows = %n, "fetched {rows} rows");
73//! imetric!("rows_fetched", "count", correlation_id = cid, region = "eu", n);
74//! fmetric!("fetch_ms", "ms", "http.method" = "GET", elapsed_ms);
75//! ```
76//!
77//! A bare value must implement [`PropertyValue`](property_value::PropertyValue) (strings do and
78//! are borrowed without a copy). `%value` formats with `Display` and `?value` with `Debug`, at
79//! the cost of one `String` allocation; those and bare values are only evaluated when the log
80//! entry is enabled. A precomputed `&'static PropertySet` is spread as the last entry with
81//! `..set`, and the pairs before it override its entries:
82//!
83//! ```rust,ignore
84//! imetric!("rows_fetched", "count", correlation_id = cid, ..SET, n);
85//! ```
86//!
87//! On the query side the values are ordinary properties:
88//! `property_get(properties, 'correlation_id')`.
89//!
90//! In analytics some property names override the row's columns: `level` and `target` for logs,
91//! `target`, `name` and `unit` for metrics. The macros reject those names as keys (`target`
92//! belongs in `target: ..` before the other arguments); an override arrives through a `..set`
93//! spread, a runtime [`DynProperty`](property_set::DynProperty) slice, or the
94//! [`imetric_dyn!`]/[`fmetric_dyn!`] macros, which set `name` and `unit`. A dynamic `level` must
95//! be a valid level name or the block fails to parse. Interop logs (the `tracing` layer) keep
96//! their level and target unchanged.
97//!
98//! # Manual Span Scopes
99//!
100//! For fine-grained control within a function, use [`span_scope!`]:
101//!
102//! ```rust,ignore
103//! use micromegas_tracing::prelude::*;
104//!
105//! fn process_batch(items: &[Item]) {
106//! span_scope!("process_batch");
107//!
108//! for item in items {
109//! span_scope!("process_item");
110//! // Process each item...
111//! }
112//! }
113//! ```
114//!
115//! # Span properties
116//!
117//! A span can carry properties on its end event, so that it reports its results (row counts,
118//! cache hit or miss, an error status) as well as the context the caller attaches. Put per-call
119//! context there rather than in a runtime name, which keeps span names low-cardinality. With
120//! `name =`, the scope macros return the guard; the property list is the one the log macros take,
121//! and `set_property` adds values later:
122//!
123//! ```rust,ignore
124//! use micromegas_tracing::prelude::*;
125//!
126//! let mut span = span_scope!(name = "fetch_rows", region = "eu", request = %req_id);
127//! let rows = fetch()?; // an early return still records region and request
128//! span.set_property("rows", rows.len());
129//! span.set_property("cache", if hit { "hit" } else { "miss" });
130//! ```
131//!
132//! `#[span_fn(key = expr, ..)]` attaches properties to a whole-function span; the values are
133//! evaluated from the arguments when the function is called and recorded on the end event:
134//!
135//! ```rust,ignore
136//! #[span_fn(view = view.get_view_set_name())]
137//! async fn materialize(view: Arc<dyn View>) -> Result<()> { /* ... */ }
138//! ```
139//!
140//! An async span takes a closure that receives the output of the future:
141//!
142//! ```rust,ignore
143//! let rows = instrument_named!(fetch(id), "fetch", |out, span| {
144//! if let Ok(rows) = out {
145//! span.set_property("rows", rows.len());
146//! }
147//! })
148//! .await;
149//! ```
150//!
151//! Gotchas:
152//!
153//! - `let _ = span_scope!(name = ..)` drops the guard at once, like any `let _`. Bind a name.
154//! - A span that never ends, or that is cut at the edge of a query range, has no properties.
155//! - Deploy analytics before instrumented code that records span properties.
156//!
157//! # Initialization
158//!
159//! Libraries should not initialize tracing - that's the application's responsibility.
160//! Applications typically use `#[micromegas_main]` from the `micromegas` crate, or
161//! manually set up guards:
162//!
163//! ```
164//! use micromegas_tracing::{guards, event};
165//!
166//! // Application initialization (libraries should NOT do this)
167//! let _tracing_guard = guards::TracingSystemGuard::new(
168//! 8 * 1024 * 1024, // log buffer size
169//! 1024 * 1024, // metrics buffer size
170//! 16 * 1024 * 1024, // spans buffer size
171//! std::sync::Arc::new(event::NullEventSink {}),
172//! std::collections::HashMap::new(),
173//! true, // Enable CPU tracing
174//! );
175//! let _thread_guard = guards::TracingThreadGuard::new();
176//! ```
177//!
178//! # Architecture
179//!
180//! Unlike other tracing crates, this library collects events into a stream rather than
181//! providing per-event hooks. Events are serialized to a binary format using `transit`,
182//! enabling efficient in-process buffering and network transmission.
183//!
184
185// crate-specific lint exceptions:
186#![allow(
187 unsafe_code,
188 missing_docs,
189 clippy::missing_errors_doc,
190 clippy::inline_always
191)]
192
193// dispatch: use wasm version on wasm32
194#[cfg(not(target_arch = "wasm32"))]
195pub mod dispatch;
196#[cfg(target_arch = "wasm32")]
197#[path = "dispatch_wasm.rs"]
198pub mod dispatch;
199
200#[cfg(not(target_arch = "wasm32"))]
201pub mod cpu_brand;
202pub mod errors;
203pub mod event;
204pub mod guards;
205#[cfg(not(target_arch = "wasm32"))]
206pub mod images;
207pub mod levels;
208pub mod logs;
209pub mod metrics;
210pub mod panic_hook;
211pub mod process_info;
212pub mod property_value;
213pub mod source_path;
214pub mod spans;
215pub mod time;
216
217// Native-only: full on native, stubs in lib.rs for wasm32
218#[cfg(not(target_arch = "wasm32"))]
219pub mod dyn_deps;
220#[cfg(not(target_arch = "wasm32"))]
221pub mod property_set;
222#[cfg(not(target_arch = "wasm32"))]
223pub mod static_set_cache;
224
225#[cfg(target_arch = "wasm32")]
226pub mod static_set_cache {
227 use crate::property_set::PropertySet;
228
229 /// Only the empty set exists on wasm32.
230 pub struct StaticSetCache<const M: usize>;
231
232 impl<const M: usize> StaticSetCache<M> {
233 pub const fn new() -> Self {
234 Self
235 }
236
237 pub fn get(
238 &self,
239 _base: &'static PropertySet,
240 _pairs: [(&'static str, &'static str); M],
241 ) -> &'static PropertySet {
242 PropertySet::empty()
243 }
244 }
245
246 impl<const M: usize> Default for StaticSetCache<M> {
247 fn default() -> Self {
248 Self::new()
249 }
250 }
251}
252
253#[cfg(target_arch = "wasm32")]
254pub mod property_set {
255 /// Stub for EventSink trait compatibility — never constructed on wasm32
256 pub struct Property;
257 /// Stub for dispatch function signatures — only the empty set exists on wasm32
258 pub struct PropertySet;
259
260 impl PropertySet {
261 pub fn empty() -> &'static Self {
262 static EMPTY: PropertySet = PropertySet;
263 &EMPTY
264 }
265 }
266
267 /// Only the empty set exists on wasm32.
268 pub fn callsite_set(
269 _cell: &'static std::sync::OnceLock<&'static PropertySet>,
270 _pairs: &'static [(&'static str, &'static str)],
271 ) -> &'static PropertySet {
272 PropertySet::empty()
273 }
274
275 pub fn static_value(v: &'static str) -> &'static str {
276 v
277 }
278
279 /// A property whose value is not `'static`. The name is `'static` (`new`) or block-scoped
280 /// (`with_dyn_name`).
281 #[derive(Debug, Clone, Copy)]
282 pub struct DynProperty<'a> {
283 name: &'a str,
284 value: &'a str,
285 }
286
287 impl<'a> DynProperty<'a> {
288 pub const fn new(name: &'static str, value: &'a str) -> Self {
289 Self { name, value }
290 }
291
292 pub const fn with_dyn_name(name: &'a str, value: &'a str) -> Self {
293 Self { name, value }
294 }
295
296 pub fn name(&self) -> &'a str {
297 self.name
298 }
299
300 pub fn value(&self) -> &'a str {
301 self.value
302 }
303 }
304}
305
306// Native-only modules (entirely transit-dependent)
307#[cfg(not(target_arch = "wasm32"))]
308pub use dispatch::send_image;
309#[cfg(not(target_arch = "wasm32"))]
310pub mod flush_monitor;
311#[cfg(not(target_arch = "wasm32"))]
312pub mod intern_string;
313#[cfg(not(target_arch = "wasm32"))]
314pub mod parsing;
315#[cfg(not(target_arch = "wasm32"))]
316pub mod static_string_ref;
317#[cfg(not(target_arch = "wasm32"))]
318pub mod string_id;
319#[cfg(not(target_arch = "wasm32"))]
320pub mod test_utils;
321
322#[cfg(feature = "tokio")]
323pub mod runtime;
324
325#[macro_use]
326mod macros;
327
328#[doc(hidden)]
329pub use micromegas_tracing_proc_macros::__log_impl;
330
331/// Commonly used items for convenient importing - includes macros, types, and traits
332pub mod prelude {
333 pub use crate::levels::*;
334 pub use crate::process_info::*;
335 pub use crate::property_set::DynProperty;
336 #[cfg(feature = "tokio")]
337 pub use crate::runtime::TracingRuntimeExt;
338 #[cfg(feature = "tokio")]
339 pub use crate::spans::spawn_with_context;
340 pub use crate::spans::{
341 InstrumentFuture, InstrumentedFuture, InstrumentedNamedFuture, SpanContextFuture,
342 current_span_id,
343 };
344 pub use crate::time::*;
345 pub use crate::{
346 debug, error, fatal, fmetric, fmetric_dyn, imetric, imetric_dyn, info, instrument_named,
347 instrument_named_dyn, log, log_enabled, span_async_named, span_async_named_dyn,
348 span_fn_future, span_scope, span_scope_named, span_scope_named_dyn, static_span_desc,
349 static_span_location, trace, warn,
350 };
351 pub use micromegas_tracing_proc_macros::*;
352}