|
| 1 | +# Tutorial: Recording a Trace with `runtime_tracing` |
| 2 | + |
| 3 | +This guide shows how to capture execution data from a program and write it in the |
| 4 | +`runtime_tracing` format. |
| 5 | + |
| 6 | +## Add the crate |
| 7 | + |
| 8 | +Add the library to your `Cargo.toml`: |
| 9 | + |
| 10 | +```toml |
| 11 | +runtime_tracing = "0.14.1" |
| 12 | +``` |
| 13 | + |
| 14 | +## Basic usage |
| 15 | + |
| 16 | +Create a `NonStreamingTraceWriter`, record a few events and store them as JSON. |
| 17 | + |
| 18 | +```rust |
| 19 | +use runtime_tracing::{ |
| 20 | + NonStreamingTraceWriter, TraceEventsFileFormat, TraceWriter, Line, |
| 21 | + TypeKind, ValueRecord, NONE_VALUE, |
| 22 | +}; |
| 23 | +use std::path::Path; |
| 24 | + |
| 25 | +fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 26 | + // Prepare the tracer |
| 27 | + let mut tracer = NonStreamingTraceWriter::new("example_program", &[]); |
| 28 | + tracer.set_format(TraceEventsFileFormat::Json); |
| 29 | + |
| 30 | + // Record some events |
| 31 | + let src = Path::new("example.rs"); |
| 32 | + tracer.start(src, Line(1)); |
| 33 | + tracer.register_step(src, Line(1)); |
| 34 | + |
| 35 | + let value = ValueRecord::Int { |
| 36 | + i: 42, |
| 37 | + type_id: tracer.ensure_type_id(TypeKind::Int, "i32"), |
| 38 | + }; |
| 39 | + tracer.register_variable_with_full_value("answer", value); |
| 40 | + tracer.register_return(NONE_VALUE); |
| 41 | + |
| 42 | + // Write the trace files |
| 43 | + tracer.begin_writing_trace_metadata(Path::new("trace_metadata.json"))?; |
| 44 | + tracer.begin_writing_trace_paths(Path::new("trace_paths.json"))?; |
| 45 | + tracer.begin_writing_trace_events(Path::new("trace.json"))?; |
| 46 | + tracer.finish_writing_trace_events()?; |
| 47 | + tracer.finish_writing_trace_metadata()?; |
| 48 | + tracer.finish_writing_trace_paths()?; |
| 49 | + Ok(()) |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +This minimal example generates the three JSON files expected by the |
| 54 | +CodeTracer debugger. |
| 55 | + |
| 56 | +For more complex scenarios, such as streaming traces or binary formats, |
| 57 | +see the APIs in `tracer.rs` and the tests in `src/lib.rs`. |
0 commit comments