linera_service/tracing/chrome.rs
1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _};
5
6/// Guard that flushes Chrome trace file when dropped.
7///
8/// Store this guard in a variable that lives for the duration of your program.
9/// When it's dropped, the trace file will be completed and closed.
10pub type ChromeTraceGuard = tracing_chrome::FlushGuard;
11
12/// Builds a Chrome trace layer and guard.
13///
14/// Returns a subscriber and guard. The subscriber should be used with `with_default`
15/// to avoid global state conflicts.
16pub fn build(
17 log_name: &str,
18 writer: impl std::io::Write + Send + 'static,
19) -> (impl tracing::Subscriber + Send + Sync, ChromeTraceGuard) {
20 let (chrome_layer, guard) = tracing_chrome::ChromeLayerBuilder::new()
21 .writer(writer)
22 .build();
23
24 let config = crate::tracing::get_env_config(log_name);
25 let maybe_log_file_layer = config.maybe_log_file_layer();
26 let stderr_layer = config.stderr_layer();
27
28 let subscriber = tracing_subscriber::registry()
29 .with(chrome_layer)
30 .with(config.env_filter)
31 .with(maybe_log_file_layer)
32 .with(stderr_layer);
33
34 (subscriber, guard)
35}
36
37/// Initializes tracing with Chrome Trace JSON exporter.
38///
39/// Returns a guard that must be kept alive for the duration of the program.
40/// When the guard is dropped, the trace data is flushed and completed.
41///
42/// Exports traces to Chrome Trace JSON format which can be visualized in:
43/// - Chrome: `chrome://tracing`
44/// - Perfetto UI: <https://ui.perfetto.dev>
45///
46/// Note: Uses `try_init()` to avoid panicking if a global subscriber is already set.
47/// In that case, tracing may not work as expected.
48pub fn init(log_name: &str, writer: impl std::io::Write + Send + 'static) -> ChromeTraceGuard {
49 let (subscriber, guard) = build(log_name, writer);
50 let _ = subscriber.try_init();
51 guard
52}