Involved Source Filesevents.gohistogram.go
Package trace implements tracing of requests and long-lived objects.
It exports HTTP interfaces on /debug/requests and /debug/events.
A trace.Trace provides tracing for short-lived objects, usually requests.
A request handler might be implemented like this:
func fooHandler(w http.ResponseWriter, req *http.Request) {
tr := trace.New("mypkg.Foo", req.URL.Path)
defer tr.Finish()
...
tr.LazyPrintf("some event %q happened", str)
...
if err := somethingImportant(); err != nil {
tr.LazyPrintf("somethingImportant failed: %v", err)
tr.SetError()
}
}
The /debug/requests HTTP endpoint organizes the traces by family,
errors, and duration. It also provides histogram of request duration
for each family.
A trace.EventLog provides tracing for long-lived objects, such as RPC
connections.
// A Fetcher fetches URL paths for a single domain.
type Fetcher struct {
domain string
events trace.EventLog
}
func NewFetcher(domain string) *Fetcher {
return &Fetcher{
domain,
trace.NewEventLog("mypkg.Fetcher", domain),
}
}
func (f *Fetcher) Fetch(path string) (string, error) {
resp, err := http.Get("http://" + f.domain + "/" + path)
if err != nil {
f.events.Errorf("Get(%q) = %v", path, err)
return "", err
}
f.events.Printf("Get(%q) = %s", path, resp.Status)
...
}
func (f *Fetcher) Close() error {
f.events.Finish()
return nil
}
The /debug/events HTTP endpoint organizes the event logs by family and
by time since the last error. The expanded view displays recent log
entries and the log's call stack.
Package-Level Type Names (total 22, in which 2 are exported)
/* sort exporteds by: | */
An EventLog provides a log of events associated with a specific object.
Errorf is like Printf, but it marks this event as an error.
Finish declares that this event log is complete.
The event log should not be used after calling this method.
Printf formats its arguments with fmt.Sprintf and adds the
result to the event log.
*eventLog
func NewEventLog(family, title string) EventLog
Trace represents an active request.
Finish declares that this trace is complete.
The trace should not be used after calling this method.
LazyLog adds x to the event log. It will be evaluated each time the
/debug/requests page is rendered. Any memory referenced by x will be
pinned until the trace is finished and later discarded.
LazyPrintf evaluates its arguments with fmt.Sprintf each time the
/debug/requests page is rendered. Any memory referenced by a will be
pinned until the trace is finished and later discarded.
SetError declares that this trace resulted in an error.
SetMaxEvents sets the maximum number of events that will be stored
in the trace. This has no effect if any events have already been
added to the trace.
SetRecycler sets a recycler for the trace.
f will be called for each event passed to LazyLog at a time when
it is no longer required, whether while the trace is still active
and the event is discarded, or when a completed trace is discarded.
SetTraceInfo sets the trace info for the trace.
This is currently unused.
*trace
func FromContext(ctx context.Context) (tr Trace, ok bool)
func New(family, title string) Trace
func NewContext(ctx context.Context, tr Trace) context.Context
discarded represents a number of discarded events.
It is stored as *discarded to make it easier to update in-place.
(*discarded) String() string
*discarded : expvar.Var
*discarded : fmt.Stringer
*discarded : context.stringer
*discarded : github.com/aws/smithy-go/middleware.stringer
*discarded : runtime.stringer
An event is a timestamped log entry in a trace.
// since previous event in trace
// whether this event is on a different day to the previous event
// whether this event was passed via LazyLog
// whether this event contains sensitive information
// string or fmt.Stringer
Whentime.Time
WhenString returns a string representation of the elapsed time of the event.
It will include the date if midnight was crossed.
An eventLog represents an active event log.
Family is the top-level grouping of event logs to which this belongs.
LastErrorTimetime.Time
Timing information.
Title is the title of this event log.
discardedintevents[]logEntry
Append-only sequence of events.
TODO(sameer): change this to a ring buffer to avoid the array copy
when we hit maxEventsPerLog.
// how many buckets this is in
Call stack where this event log was created.
(*eventLog) ElapsedTime() string(*eventLog) Errorf(format string, a ...interface{})(*eventLog) Events() []logEntry(*eventLog) Finish()(*eventLog) Printf(format string, a ...interface{})(*eventLog) Stack() string(*eventLog) When() string
delta returns the elapsed time since the last event or the log start,
and whether it spans midnight.
L >= el.mu
(*eventLog) hasRecentError(now time.Time, maxErrAge time.Duration) bool(*eventLog) printf(isErr bool, format string, a ...interface{})(*eventLog) ref()(*eventLog) reset()(*eventLog) unref()
*eventLog : EventLog
func newEventLog() *eventLog
func freeEventLog(el *eventLog)
Free calls unref on each element of the list.
eventLogs may be sorted in reverse chronological order.
( eventLogs) Less(i, j int) bool( eventLogs) Swap(i, j int)
eventLogs : sort.Interface
histogram keeps counts of values in buckets that are spaced
out in powers of 2: 0-1, 2-3, 4-7...
histogram implements timeseries.Observable
// bucketed values for histogram
// running total of measurements
// square of running total
// holds a single value as an optimization
// number of values recorded for single value
Add adds other to h.
Clear resets the histogram to an empty state, removing all observed values.
CopyFrom copies from other, which must be a *histogram, into h.
Multiply scales the histogram by the specified ratio.
New creates a new histogram.
(*histogram) String() string
addMeasurement records a value measurement observation to the histogram.
(*histogram) allocateBuckets()
Average returns the average value of recorded observations.
(*histogram) html() template.HTML
Median returns the estimated median of the observed values.
newData returns data representing h for use in distTmpl.
PercentileBoundary estimates the value that the given fraction of recorded
observations are less than.
StandardDeviation returns the standard deviation of recorded observations.
Total returns the number of recorded observations.
Variance returns the variance of recorded observations.
*histogram : golang.org/x/net/internal/timeseries.Observable
*histogram : expvar.Var
*histogram : fmt.Stringer
*histogram : context.stringer
*histogram : github.com/aws/smithy-go/middleware.stringer
*histogram : runtime.stringer
A logEntry is a timestamped log entry in an event log.
// since previous event in log
IsErrbool
// whether this event is on a different day to the previous event
WhatstringWhentime.Time
WhenString returns a string representation of the elapsed time of the event.
It will include the date if midnight was crossed.
trace represents an active or complete request,
either sent or received by this program.
// Elapsed time for this trace, zero while active.
Family is the top-level grouping of traces to which this belongs.
// Whether this trace resulted in an error.
Start time of the this trace.
Title is the title of this trace.
// scratch space to avoid allocation
// Append-only sequence of events (modulo discards).
// preallocated buffer in case we only log a few events
// where finish was called, if DebugUseAfterFinish is set
maxEventsintmusync.RWMutexrecyclerfunc(interface{})
// how many buckets this is in
spanIDuint64
// Trace information if non-zero.
(*trace) ElapsedTime() string(*trace) Events() []event(*trace) Finish()(*trace) LazyLog(x fmt.Stringer, sensitive bool)(*trace) LazyPrintf(format string, a ...interface{})(*trace) SetError()(*trace) SetMaxEvents(m int)(*trace) SetRecycler(f func(interface{}))(*trace) SetTraceInfo(traceID, spanID uint64)(*trace) When() string(*trace) addEvent(x interface{}, recyclable, sensitive bool)
delta returns the elapsed time since the last event or the trace start,
and whether it spans midnight.
L >= tr.mu
(*trace) ref()(*trace) reset()(*trace) unref()
*trace : Trace
func newTrace() *trace
func freeTrace(tr *trace)
traceBucket represents a size-capped bucket of historic traces,
along with a condition for a trace to belong to the bucket.
Condcondbuf[10]*trace
// <= tracesPerBucket
Ring buffer implementation of a fixed-size FIFO queue.
// < tracesPerBucket
(*traceBucket) Add(tr *trace)
Copy returns a copy of the traces in the bucket.
If tracedOnly is true, only the traces with trace information will be returned.
The logs will be ref'd before returning; the caller should call
the Free method when it is done with them.
TODO(dsymonds): keep track of traced requests in separate buckets.
(*traceBucket) Empty() bool
func lookupBucket(fam string, b int) *traceBucket
Free calls unref on each element of the list.
traceList may be sorted in reverse chronological order.
( traceList) Less(i, j int) bool( traceList) Swap(i, j int)
traceList : sort.Interface
func getActiveTraces(fam string) traceList
Package-Level Functions (total 30, in which 8 are exported)
Events responds with a page of events collected by EventLogs.
The package initialization registers it in http.DefaultServeMux
at /debug/events.
It performs authorization by running AuthRequest.
FromContext returns the Trace bound to the context, if any.
New returns a new Trace with the specified family and title.
NewContext returns a copy of the parent context
and associates it with a Trace.
NewEventLog returns a new EventLog with the specified family name
and title.
Render renders the HTML page typically served at /debug/requests.
It does not do any auth checking. The request may be nil.
Most users will use the Traces handler.
RenderEvents renders the HTML page typically served at /debug/events.
It does not do any auth checking. The request may be nil.
Most users will use the Events handler.
Traces responds with traces from the program.
The package initialization registers it in http.DefaultServeMux
at /debug/requests.
It performs authorization by running AuthRequest.
printStackRecord prints the function + source line information
for a single stack trace.
Adapted from runtime/pprof/pprof.go.
round returns the closest int64 to the argument
Package-Level Variables (total 18, in which 2 are exported)
AuthRequest determines whether a specific request is permitted to load the
/debug/requests or /debug/events pages.
It returns two bools; the first indicates whether the page may be viewed at all,
and the second indicates whether sensitive events will be shown.
AuthRequest may be replaced by a program to customize its authorization requirements.
The default AuthRequest function returns (true, true) if and only if the request
comes from localhost/127.0.0.1/[::1].
DebugUseAfterFinish controls whether to debug uses of Trace values after finishing.
FOR DEBUGGING ONLY. This will slow down the program.