FlightRecorder continuously records execution traces into a memory buffer, keeping only the last N seconds of data and allowing you to save this recent history to a file on demand, which avoids wasting disk space and CPU on irrelevant trace information. You start by configuring the recorder, for example, to keep five seconds of data, and then you start it early in your program. While your application runs normally, tracing happens quietly in the background. You can trigger a snapshot of the trace when an event of interest occurs or when you send the process a signal, such as SIGUSR1, and then you can inspect the snapshot using go tool trace.
An example : a web server that saves a trace when a slow request happens
server.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"runtime/trace"
"time"
)
func saveTrace(fr *trace.FlightRecorder) error {
if !fr.Enabled() {
return fmt.Errorf("flight recorder is not enabled")
}
file, err := os.Create("trace.out")
if err != nil {
return fmt.Errorf("failed to create trace file: %w", err)
}
defer file.Close()
n, err := fr.WriteTo(file)
if err != nil {
return fmt.Errorf("failed to write trace data: %w", err)
}
fmt.Printf("Wrote %d bytes to trace.out\n", n)
return nil
}
func main() {
fmt.Printf("PID: %d\n", os.Getpid())
cfg := trace.FlightRecorderConfig{MinAge: 5 * time.Second}
fr := trace.NewFlightRecorder(cfg)
if err := fr.Start(); err != nil {
log.Fatalf("Failed to start flight recorder: %v", err)
}
defer fr.Stop()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello! Time: %v\n", time.Now())
})
http.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Slow request detected...")
time.Sleep(3 * time.Second)
if err := saveTrace(fr); err != nil {
log.Printf("Failed to save trace: %v", err)
}
fmt.Fprintf(w, "Slow request completed\n")
})
fmt.Println("Server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
run the command go run server.go
1. Access the URL in web browser : http://localhost:8080/
2. Access the URL in another tab : http://localhost:8080/slow
The /slow request will simulate slow work and save the last 5 seconds of trace data into trace.out.
The you can access the trace details in browser