Documentation
¶
Overview ¶
Package trace contains facilities for programs to generate traces for the Go execution tracer.
Tracing runtime activities ¶
The execution trace captures a wide range of execution events such as goroutine creation/blocking/unblocking, syscall enter/exit/block, GC-related events, changes of heap size, processor start/stop, etc. When CPU profiling is active, the execution tracer makes an effort to include those samples as well. A precise nanosecond-precision timestamp and a stack trace is captured for most events. The generated trace can be interpreted using `go tool trace`.
Support for tracing tests and benchmarks built with the standard testing package is built into `go test`. For example, the following command runs the test in the current directory and writes the trace file (trace.out).
go test -trace=trace.out
This runtime/trace package provides APIs to add equivalent tracing support to a standalone program. See the Example that demonstrates how to use this API to enable tracing.
There is also a standard HTTP interface to trace data. Adding the following line will install a handler under the /debug/pprof/trace URL to download a live trace:
import _ "net/http/pprof"
See the net/http/pprof package for more details about all of the debug endpoints installed by this import.
User annotation ¶
Package trace provides user annotation APIs that can be used to log interesting events during execution.
There are three types of user annotations: log messages, regions, and tasks.
Log emits a timestamped message to the execution trace along with additional information such as the category of the message and which goroutine called Log. The execution tracer provides UIs to filter and group goroutines using the log category and the message supplied in Log.
A region is for logging a time interval during a goroutine's execution. By definition, a region starts and ends in the same goroutine. Regions can be nested to represent subintervals. For example, the following code records four regions in the execution trace to trace the durations of sequential steps in a cappuccino making operation.
trace.WithRegion(ctx, "makeCappuccino", func() { // orderID allows to identify a specific order // among many cappuccino order region records. trace.Log(ctx, "orderID", orderID) trace.WithRegion(ctx, "steamMilk", steamMilk) trace.WithRegion(ctx, "extractCoffee", extractCoffee) trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee) })
A task is a higher-level component that aids tracing of logical operations such as an RPC request, an HTTP request, or an interesting local operation which may require multiple goroutines working together. Since tasks can involve multiple goroutines, they are tracked via a context.Context object. NewTask creates a new task and embeds it in the returned context.Context object. Log messages and regions are attached to the task, if any, in the Context passed to Log and WithRegion.
For example, assume that we decided to froth milk, extract coffee, and mix milk and coffee in separate goroutines. With a task, the trace tool can identify the goroutines involved in a specific cappuccino order.
ctx, task := trace.NewTask(ctx, "makeCappuccino") trace.Log(ctx, "orderID", orderID) milk := make(chan bool) espresso := make(chan bool) go func() { trace.WithRegion(ctx, "steamMilk", steamMilk) milk <- true }() go func() { trace.WithRegion(ctx, "extractCoffee", extractCoffee) espresso <- true }() go func() { defer task.End() // When assemble is done, the order is complete. <-espresso <-milk trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee) }()
The trace tool computes the latency of a task by measuring the time between the task creation and the task end and provides latency distributions for each task type found in the trace.
Example ¶
この例は、trace パッケージを使用して Go プログラムの実行をトレースする方法を示しています。トレースの出力は、ファイル trace.out に書き込まれます。
f, err := os.Create("trace.out") if err != nil { log.Fatalf("failed to create trace output file: %v", err) } defer func() { if err := f.Close(); err != nil { log.Fatalf("failed to close trace file: %v", err) } }() if err := trace.Start(f); err != nil { log.Fatalf("failed to start trace: %v", err) } defer trace.Stop() // ここにあなたのプログラムを書く RunMyProgram()
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsEnabled ¶ added in v1.11.0
func IsEnabled() bool
IsEnabled はトレースが有効かどうかを報告します。 この情報はアドバイザリー(助言的)です。トレースの状態は この関数が返るまでに変更されている可能性があります。
func Log ¶ added in v1.11.0
Logは与えられたカテゴリとメッセージでワンオフのイベントを送信します。 カテゴリは空にすることができ、APIはシステム内に一握りのユニークなカテゴリしか存在しないと仮定します。
func Start ¶
Start は現在のプログラムのトレースを有効にします。 トレース中は、トレースはバッファリングされ、w に書き込まれます。 トレースが既に有効になっている場合、Start はエラーを返します。
func WithRegion ¶ added in v1.11.0
WithRegionは、呼び出し元のgoroutineに関連付けられた領域を開始し、fnを実行し、その後領域を終了します。もしコンテキストにタスクがある場合、領域はそのタスクに関連付けられます。そうでない場合、領域はバックグラウンドのタスクにアタッチされます。 regionTypeは領域を分類するために使用されるため、ユニークなregionTypeはごくわずかであるべきです。
Types ¶
type Region ¶ added in v1.11.0
type Region struct {
// contains filtered or unexported fields
}
Regionは、実行時間の区間がトレースされるコードの領域です。
func StartRegion ¶ added in v1.11.0
StartRegionはリージョンを開始して返します。 戻り値となるリージョンの[Region.End]メソッドは、 リージョンを開始した同じゴルーチンから呼び出す必要があります。 各ゴルーチン内では、リージョンはネストする必要があります。 つまり、このリージョンを終了する前に、このリージョンよりも後に開始されたリージョンを終了する必要があります。 推奨される使用法は
defer trace.StartRegion(ctx, "myTracedRegion").End()
type Task ¶ added in v1.11.0
type Task struct {
// contains filtered or unexported fields
}
Taskは、ユーザー定義の論理的な操作をトレースするためのデータ型です。
func NewTask ¶ added in v1.11.0
NewTaskはタスクの種類(taskType)でタスクインスタンスを作成し、 タスクを持つContextとともに返します。 もし入力のContextにタスクが含まれている場合、新しいタスクはそのサブタスクとなります。
タスクタイプはタスクインスタンスを分類するために使用されます。Go実行トレーサのような 分析ツールは、システムに一意のタスクタイプが有限であると見なすことがあります。
返されるTaskの[Task.End]メソッドはタスクの終了をマークするために使用されます。 トレースツールは、タスクの作成とEndメソッドの呼び出しの間の時間をタスクのレイテンシとして測定し、 レイテンシの分布をタスクタイプごとに提供します。 Endメソッドが複数回呼び出された場合、レイテンシの測定には最初の呼び出しぶんのみ使用されます。
ctx、task := trace.NewTask(ctx, "awesomeTask") trace.WithRegion(ctx, "preparation", prepWork) // タスクの準備 go func() { // 別のゴルーチンでタスクの処理を続ける。
defer task.End() trace.WithRegion(ctx, "remainingWork", remainingWork) }()