Standard library / runtime/trace

trace.WithRegion()

Execute a callback inside a named region on the current goroutine; its end is recorded even if the callback panics. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func WithRegion(ctx context.Context, regionType string, fn func())

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext carrying profiling labels or an execution trace task.
regionTypestringLow-cardinality name for the traced region type.
fnfunc()Function executed inside the region on the calling goroutine.

Working Example

Example Snippetgo
package main
import (  "bytes"  "context"  "fmt"  "runtime/trace")
func main() {  var b bytes.Buffer  if err := trace.Start(&b); err != nil {    panic(err)  }  called := false  trace.WithRegion(context.Background(), "parse", func() { called = true })  trace.Stop()  fmt.Println(called && b.Len() > 0)}
Go Reference