trace

package
v1.26.1 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

traceパッケージには、Go実行トレーサーのためのトレースを生成するプログラムの機能が含まれています。

Tracing runtime activities

実行トレースは、ゴルーチンの作成/ブロック/アンブロック、システムコールの入力/出力/ブロック、 GC関連のイベント、ヒープサイズの変更、プロセッサの開始/停止など、幅広い実行イベントをキャプチャします。 CPUプロファイリングがアクティブな場合、実行トレーサーはこれらのサンプルも含めるように努力します。 ほとんどのイベントに対して、正確なナノ秒精度のタイムスタンプとスタックトレースがキャプチャされます。 生成されたトレースは `go tool trace` を使用して解釈することができます。

標準のテストパッケージで構築されたテストとベンチマークのトレースのサポートは、 `go test`に組み込まれています。例えば、以下のコマンドは現在のディレクトリでテストを実行し、 トレースファイル(trace.out)を書き出します。

go test -trace=trace.out

このruntime/traceパッケージは、同等のトレーシングサポートをスタンドアロンのプログラムに追加するためのAPIを提供します。 このAPIを使用してトレーシングを有効にする方法を示す例を参照してください。

また、トレースデータには標準的なHTTPインターフェースもあります。以下の行を追加すると、 /debug/pprof/trace URLの下にハンドラがインストールされ、ライブトレースをダウンロードできます:

import _ "net/http/pprof"

このインポートによってインストールされたすべてのデバッグエンドポイントについての詳細は、 net/http/pprof パッケージを参照してください。

User annotation

traceパッケージは、実行中の興味深いイベントをログに記録するために使用できる ユーザー注釈APIを提供します。

ユーザー注釈には3つのタイプがあります:ログメッセージ、領域、タスク。

Log は、メッセージのカテゴリや Log を呼び出したゴルーチンなどの追加情報とともに、 実行トレースにタイムスタンプ付きのメッセージを発行します。実行トレーサーは、 ログカテゴリと Log で提供されるメッセージを使用してゴルーチンをフィルタリング およびグループ化するUIを提供します。

リージョンは、ゴルーチンの実行中の時間間隔をログに記録するためのものです。 定義上、リージョンは同じゴルーチンで開始し終了します。 リージョンは、サブインターバルを表すためにネストすることができます。 例えば、次のコードは、カプチーノ作成操作の連続したステップの期間をトレースするために、 実行トレースに4つのリージョンを記録します。

trace.WithRegion(ctx, "makeCappuccino", func() {

   // orderIDは、多くのカプチーノ注文領域レコードの中から特定の注文を識別するために使用します。
   trace.Log(ctx, "orderID", orderID)

   trace.WithRegion(ctx, "steamMilk", steamMilk)
   trace.WithRegion(ctx, "extractCoffee", extractCoffee)
   trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
})

タスクは、RPCリクエスト、HTTPリクエスト、または複数のゴルーチンが協力して行う必要がある 興味深いローカル操作など、論理的な操作のトレースを支援する高レベルのコンポーネントです。 タスクは複数のゴルーチンを含む可能性があるため、context.Context オブジェクトを介して追跡されます。 NewTask は新しいタスクを作成し、それを返された context.Context オブジェクトに埋め込みます。 ログメッセージとリージョンは、LogWithRegion に渡されたContextにあるタスク(存在する場合)に添付されます。

例えば、ミルクを泡立て、コーヒーを抽出し、ミルクとコーヒーを別々のゴルーチンで混ぜることにしました。 タスクを使用すると、トレースツールは特定のカプチーノ注文に関与するゴルーチンを識別できます。

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() // アセンブルが完了したら、注文は完了します。
        <-espresso
        <-milk
        trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
}()

トレースツールは、タスクの作成とタスクの終了の間の時間を測定することでタスクの遅延を計算し、 トレース内で見つかった各タスクタイプの遅延分布を提供します。

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

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 FlightRecorder added in v1.25.0

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

FlightRecorder represents a single consumer of a Go execution trace. It tracks a moving window over the execution trace produced by the runtime, always containing the most recent trace data.

At most one flight recorder may be active at any given time, though flight recording is allowed to be concurrently active with a trace consumer using trace.Start. This restriction of only a single flight recorder may be removed in the future.

func NewFlightRecorder added in v1.25.0

func NewFlightRecorder(cfg FlightRecorderConfig) *FlightRecorder

NewFlightRecorder creates a new flight recorder from the provided configuration.

func (*FlightRecorder) Enabled added in v1.25.0

func (fr *FlightRecorder) Enabled() bool

Enabled returns true if the flight recorder is active. Specifically, it will return true if Start did not return an error, and Stop has not yet been called. It is safe to call from multiple goroutines simultaneously.

func (*FlightRecorder) Start added in v1.25.0

func (fr *FlightRecorder) Start() error

Start activates the flight recorder and begins recording trace data. Only one call to trace.Start may be active at any given time. In addition, currently only one flight recorder may be active in the program. Returns an error if the flight recorder cannot be started or is already started.

func (*FlightRecorder) Stop added in v1.25.0

func (fr *FlightRecorder) Stop()

Stop ends recording of trace data. It blocks until any concurrent WriteTo calls complete.

func (*FlightRecorder) WriteTo added in v1.25.0

func (fr *FlightRecorder) WriteTo(w io.Writer) (n int64, err error)

WriteTo snapshots the moving window tracked by the flight recorder. The snapshot is expected to contain data that is up-to-date as of when WriteTo is called, though this is not a hard guarantee. Only one goroutine may execute WriteTo at a time. An error is returned upon failure to write to w, if another WriteTo call is already in-progress, or if the flight recorder is inactive.

type FlightRecorderConfig added in v1.25.0

type FlightRecorderConfig struct {
	// MinAge is a lower bound on the age of an event in the flight recorder's window.
	//
	// The flight recorder will strive to promptly discard events older than the minimum age,
	// but older events may appear in the window snapshot. The age setting will always be
	// overridden by MaxSize.
	//
	// If this is 0, the minimum age is implementation defined, but can be assumed to be on the order
	// of seconds.
	MinAge time.Duration

	// MaxBytes is an upper bound on the size of the window in bytes.
	//
	// This setting takes precedence over MinAge.
	// However, it does not make any guarantees on the size of the data WriteTo will write,
	// nor does it guarantee memory overheads will always stay below MaxBytes. Treat it
	// as a hint.
	//
	// If this is 0, the maximum size is implementation defined.
	MaxBytes uint64
}

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