trace

package
v1.21.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2023 License: MIT Imports: 2 Imported by: 0

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

func Log(ctx context.Context, category, message string)

Logは与えられたカテゴリとメッセージでワンオフのイベントを送信します。 カテゴリは空にすることができ、APIはシステム内に一握りのユニークなカテゴリしか存在しないと仮定します。

func Logf added in v1.11.0

func Logf(ctx context.Context, category, format string, args ...any)

Logfは[Log]と似ていますが、値は指定されたフォーマット仕様を使用して整形されます。

func Start

func Start(w io.Writer) error

Start は現在のプログラムのトレースを有効にします。 トレース中は、トレースはバッファリングされ、w に書き込まれます。 トレースが既に有効になっている場合、Start はエラーを返します。

func Stop

func Stop()

Stopは現在のトレースを停止します(存在する場合)。 トレースのすべての書き込みが完了するまで、Stopは戻りません。

func WithRegion added in v1.11.0

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

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

func StartRegion(ctx context.Context, regionType string) *Region

StartRegionはリージョンを開始して返します。 戻り値となるリージョンの[Region.End]メソッドは、 リージョンを開始した同じゴルーチンから呼び出す必要があります。 各ゴルーチン内では、リージョンはネストする必要があります。 つまり、このリージョンを終了する前に、このリージョンよりも後に開始されたリージョンを終了する必要があります。 推奨される使用法は

defer trace.StartRegion(ctx, "myTracedRegion").End()

func (*Region) End added in v1.11.0

func (r *Region) End()

Endはトレースされたコード領域の終わりを示します。

type Task added in v1.11.0

type Task struct {
	// contains filtered or unexported fields
}

Taskは、ユーザー定義の論理的な操作をトレースするためのデータ型です。

func NewTask added in v1.11.0

func NewTask(pctx context.Context, taskType string) (ctx context.Context, task *Task)

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)
}()

func (*Task) End added in v1.11.0

func (t *Task) End()

End は Task によって表される操作の終了を示します。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL