github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/runtime/trace/trace.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package trace contains facilities for programs to generate trace
     6  // for Go execution tracer.
     7  //
     8  // The execution trace captures a wide range of execution events such as
     9  // goroutine creation/blocking/unblocking, syscall enter/exit/block,
    10  // GC-related events, changes of heap size, processor stop/stop, etc.
    11  // A precise nanosecond-precision timestamp and a stack trace is
    12  // captured for most events. The generated trace can be interpreted
    13  // using `go tool trace`.
    14  //
    15  // Tracing a Go program
    16  //
    17  // Support for tracing tests and benchmarks built with the standard
    18  // testing package is built into `go test`. For example, the following
    19  // command runs the test in the current directory and writes the trace
    20  // file (trace.out).
    21  //
    22  //    go test -trace=test.out
    23  //
    24  // This runtime/trace package provides APIs to add equivalent tracing
    25  // support to a standalone program. See the Example that demonstrates
    26  // how to use this API to enable tracing.
    27  //
    28  // There is also a standard HTTP interface to profiling data. Adding the
    29  // following line will install handlers under the /debug/pprof/trace URL
    30  // to download live profiles:
    31  //
    32  //     import _ "net/http/pprof"
    33  //
    34  // See the net/http/pprof package for more details.
    35  package trace
    36  
    37  import (
    38  	"io"
    39  	"runtime"
    40  )
    41  
    42  // Start enables tracing for the current program.
    43  // While tracing, the trace will be buffered and written to w.
    44  // Start returns an error if tracing is already enabled.
    45  func Start(w io.Writer) error {
    46  	if err := runtime.StartTrace(); err != nil {
    47  		return err
    48  	}
    49  	go func() {
    50  		for {
    51  			data := runtime.ReadTrace()
    52  			if data == nil {
    53  				break
    54  			}
    55  			w.Write(data)
    56  		}
    57  	}()
    58  	return nil
    59  }
    60  
    61  // Stop stops the current tracing, if any.
    62  // Stop only returns after all the writes for the trace have completed.
    63  func Stop() {
    64  	runtime.StopTrace()
    65  }