Getting started
editInstall the package
Add the Meziantou.Framework.ChromiumTracing package to a project:
dotnet package add Meziantou.Framework.ChromiumTracingThe examples of this documentation need using Meziantou.Framework.ChromiumTracing;.
Write a trace file
Create a writer for a file, write events, and dispose the writer:
// Create a writer
await using var writer = ChromiumTracingWriter.Create("trace.json");
// Write a complete event (shows as a box in the timeline)
await writer.WriteEventAsync(new ChromiumTracingCompleteEvent
{
Name = "My Operation",
Category = "category1",
Timestamp = DateTimeOffset.UtcNow,
Duration = TimeSpan.FromMilliseconds(150),
ProcessId = Environment.ProcessId,
ThreadId = Environment.CurrentManagedThreadId,
Arguments = new Dictionary<string, object?>
{
["result"] = "success",
["count"] = 42,
},
});ChromiumTracingWriter.Create(path)creates the file, or overwrites it.- WriteEventAsync writes one event. A complete event, as here, is an operation with a start time and a duration: the viewer shows it as a box on the row of its process and thread.
- ProcessId and ThreadId choose the row. They do not have to be real process and thread identifiers: any numbers that group the events the way you want to see them work.
- The writer is
IAsyncDisposableonly: declare it withawait using. Disposing it closes the JSON array and the file.
Measure an operation
To trace an operation of your program, take the start time, measure the duration with a Stopwatch, and write a complete event when the operation ends:
using var stream = new MemoryStream();
await using (var writer = new ChromiumTracingWriter(stream))
{
var start = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
// ... the operation to measure ...
await writer.WriteEventAsync(new ChromiumTracingCompleteEvent
{
Name = "Compile",
Category = "build",
Timestamp = start,
Duration = stopwatch.Elapsed,
ProcessId = Environment.ProcessId,
ThreadId = Environment.CurrentManagedThreadId,
});
}
using var trace = JsonDocument.Parse(stream.ToArray());
Assert.Equal(["X"], trace.RootElement.EnumerateArray().Select(item => item.GetProperty("ph").GetString()).ToArray());The next examples of this documentation write to a MemoryStream and check the JSON they produce. Replace the stream with ChromiumTracingWriter.Create("trace.json") to get a file. See Files and streams.
View the trace
- Open
chrome://tracingin Chrome, oredge://tracingin Edge. - Click Load and select the trace file.
- Zoom and pan the timeline, and select an event to see its properties and arguments.
Other viewers read the same format, such as Perfetto UI.
Next steps
- Event types: nested durations, counters, asynchronous operations and more.
- Event properties: categories, arguments and colors.