Documentation
¶
Overview ¶
Package webpprof provides a Telescope-like request profiler and debug toolbar for Go web applications.
It records bounded, redacted diagnostic entries for inbound requests, SQL, cache operations, jobs, logs, email, outbound HTTP calls, schedules, callables, measured tasks, middleware, exceptions, and custom events. Related work can be correlated through context.Context and inspected in the embedded dashboard.
Getting started ¶
Use New to mount the profiler on an existing HTTP router, or Start to run it on a dedicated address. HTTP framework and dependency adapters live under github.com/levskiy0/webpprof/profiler.
Capture lifecycle ¶
BeginRequest and RequestCapture support manual request instrumentation. Context-aware Log methods automatically inherit request correlation, parent entry IDs, and tags. Storage is bounded by retention, event count, and byte limits.
Security ¶
The dashboard contains application data. Dedicated servers created by Start require WithToken unless the caller explicitly opts into WithUnsafeUnauthenticatedAccess. Captured JSON is redacted using the built-in sensitive-key policy, but callers should still avoid recording secrets in opaque strings.
Example ¶
Example demonstrates mounting webpprof beside an application handler.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/levskiy0/webpprof"
webpprofhttp "github.com/levskiy0/webpprof/profiler/http"
)
func main() {
mux := http.NewServeMux()
profiler := webpprof.New(
mux,
webpprof.WithUnsafeUnauthenticatedAccess(),
webpprof.WithExcludedRequests("GET /health"),
)
defer profiler.Close()
application := http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
response.WriteHeader(http.StatusNoContent)
})
mux.Handle("/api/", webpprofhttp.MiddlewareWith(profiler, application))
request := httptest.NewRequest(http.MethodGet, "/api/users", nil)
response := httptest.NewRecorder()
mux.ServeHTTP(response, request)
fmt.Println(response.Code, profiler.BasePath())
}
Output: 204 /debug/webpprof
Index ¶
- Constants
- func Enabled() bool
- func IsSensitiveKey(key string) bool
- func LogCache(cache Cache)
- func LogCacheContext(ctx context.Context, cache Cache)
- func LogCallable(callable Callable)
- func LogCallableContext(ctx context.Context, callable Callable)
- func LogEmail(email Email)
- func LogEmailContext(ctx context.Context, email Email)
- func LogEvent(event Event)
- func LogEventContext(ctx context.Context, event Event)
- func LogException(exception Exception)
- func LogExceptionContext(ctx context.Context, exception Exception)
- func LogHTTPCall(call HTTPCall)
- func LogHTTPCallContext(ctx context.Context, call HTTPCall)
- func LogJob(job Job)
- func LogJobContext(ctx context.Context, job Job)
- func LogLog(log Log)
- func LogLogContext(ctx context.Context, log Log)
- func LogMiddleware(middleware Middleware)
- func LogMiddlewareContext(ctx context.Context, middleware Middleware)
- func LogQuery(query Query)
- func LogQueryContext(ctx context.Context, query Query)
- func LogRequest(request Request)
- func LogSchedule(schedule Schedule)
- func LogScheduleContext(ctx context.Context, schedule Schedule)
- func LogTask(task Task)
- func LogTaskContext(ctx context.Context, task Task)
- func NewID() string
- func ParentEntryIDFromContext(ctx context.Context) string
- func Profile[T any](value T, integration Integration[T]) T
- func ProfileWith[T any](profiler *Profiler, value T, integration Integration[T]) T
- func RecordingEnabled(ctx context.Context) bool
- func Redact(value any)
- func ShouldCaptureRequest(request *http.Request) bool
- func Shutdown(ctx context.Context) error
- func TagsFromContext(ctx context.Context) map[string]string
- func URL() string
- func WithParentEntry(ctx context.Context, entryID string) context.Context
- func WithRequest(ctx context.Context, capture *RequestCapture) context.Context
- func WithTags(ctx context.Context, tags map[string]string) context.Context
- func WithoutCorrelation(ctx context.Context) context.Context
- func WithoutRecording(ctx context.Context) context.Context
- type Address
- type Argument
- type Cache
- type Callable
- type CallableAnalysis
- type DashboardChart
- type DashboardCounter
- type DashboardCounterGrid
- type DashboardCounterSnapshot
- type DashboardFormat
- type DashboardMetric
- type DashboardMetricMode
- type DashboardMetricSnapshot
- type DashboardOption
- func WithCPU() DashboardOption
- func WithCacheHitRate() DashboardOption
- func WithCounterGrid(grid DashboardCounterGrid) DashboardOption
- func WithCustomChart(chart DashboardChart) DashboardOption
- func WithCustomMetric(metric DashboardMetric) DashboardOption
- func WithEventMix() DashboardOption
- func WithGoMemory() DashboardOption
- func WithGoroutines() DashboardOption
- func WithQueries() DashboardOption
- func WithQueueHealth() DashboardOption
- func WithRequests() DashboardOption
- func WithSlowestOperations() DashboardOption
- type DashboardSeries
- type DashboardSeriesSnapshot
- type DashboardSnapshot
- type DashboardValueFunc
- type DashboardWidgetSnapshot
- type Email
- type Entry
- type EntryStorage
- type Event
- type EventResult
- type EventSpan
- type Exception
- type Finding
- type FindingCode
- type FindingSeverity
- type HTTPCall
- type HTTPMessage
- type Integration
- type Job
- type Kind
- type Log
- type Measurement
- func Measure(ctx context.Context, event Event, fn func(context.Context) error) Measurement
- func MeasureTask(ctx context.Context, task Task, fn func(context.Context) error) Measurement
- func MeasureValue[T any](ctx context.Context, event Event, fn func(context.Context) (T, error)) (T, Measurement)
- func MeasureValueWith[T any](profiler *Profiler, ctx context.Context, event Event, ...) (value T, measurement Measurement)
- type Meta
- type Middleware
- type MiddlewareWorkSpan
- type Option
- func Dashboard(options ...DashboardOption) Option
- func WithAllowedOrigins(origins ...string) Option
- func WithBasePath(path string) Option
- func WithBodyLimit(maxBytes int64) Option
- func WithBrowserSession(session string) Option
- func WithCallsiteKinds(kinds ...Kind) Option
- func WithDashboardTimeout(timeout time.Duration) Option
- func WithDisabledKinds(kinds ...Kind) Option
- func WithExcludedRequests(patterns ...string) Option
- func WithHTTPStatusAtLeast(status int) Option
- func WithHTTPStatusCodes(codes ...int) Option
- func WithMaxBytes(maxBytes int64) Option
- func WithMaxEvents(maxEvents int) Option
- func WithMinRequestDuration(duration time.Duration) Option
- func WithNextRequests(count int) Option
- func WithQueryCallsite(enabled bool) Option
- func WithQueueStatsTimeout(timeout time.Duration) Option
- func WithRequestFilter(filter RequestFilter) Option
- func WithRequestRetentionFilter(filter RequestRetentionFilter) Option
- func WithRequestSampleRate(rate float64) Option
- func WithRequestTags(tags map[string]string) Option
- func WithRetention(retention time.Duration) Option
- func WithSecureCookie(isSecure bool) Option
- func WithSidebarKinds(kinds ...Kind) Option
- func WithSourceLink(sourceLink SourceLinkFunc) Option
- func WithStorage(storage EntryStorage) Option
- func WithStoragePath(storagePath string) Option
- func WithStreamBuffer(size int) Option
- func WithToken(token string) Option
- func WithUnsafeUnauthenticatedAccess() Option
- type Profiler
- func (p *Profiler) AnalyzeCallable(callableID string) (CallableAnalysis, bool)
- func (p *Profiler) AnalyzeRequest(requestID string) (RequestAnalysis, bool)
- func (p *Profiler) AnalyzeSchedule(scheduleID string) (ScheduleAnalysis, bool)
- func (p *Profiler) AnalyzeTask(taskID string) (TaskAnalysis, bool)
- func (p *Profiler) BasePath() string
- func (p *Profiler) BeginRequest(request Request) *RequestCapture
- func (p *Profiler) BodyLimit() int64
- func (p *Profiler) CaptureCallsite(kind Kind) []SourceFrame
- func (p *Profiler) CaptureQueryCallsite() []SourceFrame
- func (p *Profiler) Close() error
- func (p *Profiler) DashboardSnapshot(ctx context.Context) DashboardSnapshot
- func (p *Profiler) Enabled() bool
- func (p *Profiler) LogCache(cache Cache)
- func (p *Profiler) LogCacheContext(ctx context.Context, cache Cache)
- func (p *Profiler) LogCallable(callable Callable)
- func (p *Profiler) LogCallableContext(ctx context.Context, callable Callable)
- func (p *Profiler) LogEmail(email Email)
- func (p *Profiler) LogEmailContext(ctx context.Context, email Email)
- func (p *Profiler) LogEvent(event Event)
- func (p *Profiler) LogEventContext(ctx context.Context, event Event)
- func (p *Profiler) LogException(exception Exception)
- func (p *Profiler) LogExceptionContext(ctx context.Context, exception Exception)
- func (p *Profiler) LogHTTPCall(call HTTPCall)
- func (p *Profiler) LogHTTPCallContext(ctx context.Context, call HTTPCall)
- func (p *Profiler) LogJob(job Job)
- func (p *Profiler) LogJobContext(ctx context.Context, job Job)
- func (p *Profiler) LogLog(log Log)
- func (p *Profiler) LogLogContext(ctx context.Context, log Log)
- func (p *Profiler) LogMiddleware(middleware Middleware)
- func (p *Profiler) LogMiddlewareContext(ctx context.Context, middleware Middleware)
- func (p *Profiler) LogQuery(query Query)
- func (p *Profiler) LogQueryContext(ctx context.Context, query Query)
- func (p *Profiler) LogRequest(request Request)
- func (p *Profiler) LogSchedule(schedule Schedule)
- func (p *Profiler) LogScheduleContext(ctx context.Context, schedule Schedule)
- func (p *Profiler) LogTask(task Task)
- func (p *Profiler) LogTaskContext(ctx context.Context, task Task)
- func (p *Profiler) Measure(ctx context.Context, event Event, fn func(context.Context) error) Measurement
- func (p *Profiler) MeasureTask(ctx context.Context, task Task, fn func(context.Context) error) Measurement
- func (p *Profiler) QueueStats(ctx context.Context) QueueStatsResponse
- func (p *Profiler) RegisterQueueStats(source QueueStatsSource, names ...string) QueueStatsSource
- func (p *Profiler) RuntimeStats() RuntimeStats
- func (p *Profiler) ShouldCaptureRequest(request *http.Request) bool
- func (p *Profiler) Shutdown(ctx context.Context) error
- func (p *Profiler) StartEvent(ctx context.Context, event Event) *EventSpan
- func (p *Profiler) StartTask(ctx context.Context, task Task) *TaskSpan
- func (p *Profiler) URL() string
- type Query
- type QueryPlan
- type QueryPlanIssue
- type QueryPlanIssueCode
- type QuerySpan
- type QueueState
- type QueueStats
- type QueueStatsResponse
- type QueueStatsSource
- type QueueStatsSourceFunc
- type Request
- type RequestAnalysis
- type RequestCapture
- func (c *RequestCapture) AddTags(tags map[string]string)
- func (c *RequestCapture) Finish(result RequestResult)
- func (c *RequestCapture) ID() string
- func (c *RequestCapture) LogCache(cache Cache)
- func (c *RequestCapture) LogEmail(email Email)
- func (c *RequestCapture) LogEvent(event Event)
- func (c *RequestCapture) LogException(exception Exception)
- func (c *RequestCapture) LogHTTPCall(call HTTPCall)
- func (c *RequestCapture) LogJob(job Job)
- func (c *RequestCapture) LogLog(log Log)
- func (c *RequestCapture) LogMiddleware(middleware Middleware)
- func (c *RequestCapture) LogQuery(query Query)
- func (c *RequestCapture) LogSchedule(schedule Schedule)
- func (c *RequestCapture) SetRoute(route string)
- type RequestFilter
- type RequestResult
- type RequestRetentionFilter
- type Router
- type RuntimeStats
- type Schedule
- type ScheduleAnalysis
- type Scope
- type SourceFrame
- type SourceLinkFunc
- type Stats
- type Task
- type TaskAnalysis
- type TaskResult
- type TaskSpan
Examples ¶
Constants ¶
const ( // CaptureSessionHeader can mark requests from one developer browser or // client session when WithBrowserSession is configured. CaptureSessionHeader = "X-Webpprof-Session" // CaptureSessionCookie is the browser cookie alternative to // CaptureSessionHeader. CaptureSessionCookie = "webpprof_capture" )
Variables ¶
This section is empty.
Functions ¶
func IsSensitiveKey ¶
IsSensitiveKey reports whether key matches the profiler's built-in secret names after case and separator normalization.
func LogCache ¶
func LogCache(cache Cache)
LogCache records a cache operation with the default profiler.
func LogCacheContext ¶
LogCacheContext records a cache operation with the default profiler and correlation inherited from ctx.
func LogCallable ¶ added in v0.5.0
func LogCallable(callable Callable)
LogCallable records an explicitly invoked custom command with the default profiler.
func LogCallableContext ¶ added in v0.5.0
LogCallableContext records an explicitly invoked command with the default profiler. The Callable remains an execution root while inheriting tags.
func LogEmail ¶
func LogEmail(email Email)
LogEmail records an outgoing email with the default profiler.
func LogEmailContext ¶
LogEmailContext records an email with the default profiler and correlation inherited from ctx.
func LogEvent ¶
func LogEvent(event Event)
LogEvent records a custom event with the default profiler.
func LogEventContext ¶
LogEventContext records a custom event with the default profiler and correlation inherited from ctx.
func LogException ¶
func LogException(exception Exception)
LogException records an application exception with the default profiler.
func LogExceptionContext ¶
LogExceptionContext records an exception with the default profiler and correlation inherited from ctx.
func LogHTTPCall ¶
func LogHTTPCall(call HTTPCall)
LogHTTPCall records an outbound HTTP call with the default profiler.
func LogHTTPCallContext ¶
LogHTTPCallContext records an outbound HTTP call with the default profiler and correlation inherited from ctx.
func LogJobContext ¶
LogJobContext records a job with the default profiler and correlation inherited from ctx.
func LogLogContext ¶
LogLogContext records a structured log with the default profiler and correlation inherited from ctx.
func LogMiddleware ¶ added in v0.2.0
func LogMiddleware(middleware Middleware)
LogMiddleware records middleware using the default profiler.
func LogMiddlewareContext ¶ added in v0.2.0
func LogMiddlewareContext(ctx context.Context, middleware Middleware)
LogMiddlewareContext records middleware using the default profiler and correlates it with the request capture in ctx.
func LogQuery ¶
func LogQuery(query Query)
LogQuery records a database query with the default profiler.
func LogQueryContext ¶
LogQueryContext records a query with the default profiler and inherits tags, parent entry, and request correlation from ctx.
func LogRequest ¶
func LogRequest(request Request)
LogRequest records a completed request with the default profiler.
func LogSchedule ¶
func LogSchedule(schedule Schedule)
LogSchedule records a scheduled task with the default profiler.
func LogScheduleContext ¶
LogScheduleContext records a scheduled task with the default profiler. The Schedule remains an execution root while inheriting tags.
func LogTask ¶ added in v0.5.0
func LogTask(task Task)
LogTask records a measured application task with the default profiler.
func LogTaskContext ¶ added in v0.5.0
LogTaskContext records a measured task with the default profiler. The Task remains an execution root while inheriting tags.
func NewID ¶
func NewID() string
NewID returns a random 128-bit lowercase hexadecimal identifier. It falls back to a UTC timestamp only when the system random source fails.
func ParentEntryIDFromContext ¶ added in v0.2.0
ParentEntryIDFromContext returns the current profiler parent entry ID.
func Profile ¶
func Profile[T any](value T, integration Integration[T]) T
Profile instruments value with the default profiler. It returns value unchanged when profiling is disabled or integration is nil.
func ProfileWith ¶
func ProfileWith[T any](profiler *Profiler, value T, integration Integration[T]) T
ProfileWith instruments value with an explicit profiler. It returns value unchanged when profiler or integration is nil.
func RecordingEnabled ¶
RecordingEnabled reports whether context-aware profiler integrations should record work for ctx. A nil context is treated as enabled.
func Redact ¶
func Redact(value any)
Redact replaces sensitive values in JSON-like maps and slices in place. Structs and other concrete values are left unchanged; Log methods perform a JSON round trip before applying the same policy.
func ShouldCaptureRequest ¶
ShouldCaptureRequest applies the default profiler's exclusions, filters, sampling rate, and optional request limit.
func TagsFromContext ¶ added in v0.2.0
TagsFromContext returns a copy of the profiler tags stored in ctx.
func URL ¶
func URL() string
URL returns the dashboard URL of the default dedicated server, or an empty string when the profiler is mounted into an application router.
func WithParentEntry ¶ added in v0.2.0
WithParentEntry returns a context that makes entryID the default ParentID for profiler entities recorded downstream. An explicit Meta.ParentID always takes precedence.
func WithRequest ¶
func WithRequest(ctx context.Context, capture *RequestCapture) context.Context
WithRequest associates capture with ctx so context-aware integrations append related entities to the same request.
func WithTags ¶ added in v0.2.0
WithTags returns a context carrying tags inherited by every profiler entity logged from it. When a request capture is present, the request receives the same tags. Values in tags replace values already present under the same key.
func WithoutCorrelation ¶ added in v0.5.0
WithoutCorrelation returns a context that preserves cancellation, deadlines, tags, recording state, and application values while removing webpprof request and parent-entry correlation. Execution-root integrations use it to avoid becoming children of the caller that invoked them.
Types ¶
type Argument ¶
type Argument struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
Size int64 `json:"size,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
Argument is a redacted, size-aware representation of a job argument.
type Cache ¶
type Cache struct {
Meta
Store string `json:"store,omitempty"`
Operation string `json:"operation,omitempty"`
Key string `json:"key,omitempty"`
Hit bool `json:"hit"`
TTL time.Duration `json:"ttl_ns,omitempty"`
Size int64 `json:"size,omitempty"`
Value string `json:"value,omitempty"`
Truncated bool `json:"truncated,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
}
Cache describes a cache read, write, invalidation, or lock operation.
type Callable ¶ added in v0.5.0
type Callable struct {
Meta
Name string `json:"name"`
State string `json:"state,omitempty"`
Payload any `json:"payload,omitempty"`
Result any `json:"result,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
Panic string `json:"panic,omitempty"`
}
Callable describes one explicitly invoked custom command and its outcome.
type CallableAnalysis ¶ added in v0.5.0
type CallableAnalysis struct {
CallableID string `json:"callable_id"`
CallableDurationNS int64 `json:"callable_duration_ns"`
GeneratedAt time.Time `json:"generated_at"`
Findings []Finding `json:"findings"`
}
CallableAnalysis contains automatic findings for one captured Callable execution.
type DashboardChart ¶ added in v0.2.0
type DashboardChart struct {
ID string
Title string
Description string
Unit string
Format DashboardFormat
Span int
Series []DashboardSeries
}
DashboardChart configures a time-series chart. Span is clamped to 1..4 columns and defaults to 2.
type DashboardCounter ¶ added in v0.2.0
type DashboardCounter struct {
ID string
Label string
Unit string
Format DashboardFormat
Value DashboardValueFunc
}
DashboardCounter configures one value inside a counter grid.
type DashboardCounterGrid ¶ added in v0.2.0
type DashboardCounterGrid struct {
ID string
Title string
Description string
Span int
Counters []DashboardCounter
}
DashboardCounterGrid groups related counters without charts. Span is clamped to 1..4 columns and defaults to 2.
type DashboardCounterSnapshot ¶ added in v0.2.0
type DashboardCounterSnapshot struct {
ID string `json:"id"`
Label string `json:"label"`
Unit string `json:"unit,omitempty"`
Format DashboardFormat `json:"format"`
Value float64 `json:"value"`
Error string `json:"error,omitempty"`
}
DashboardCounterSnapshot contains the latest value in a counter grid.
type DashboardFormat ¶ added in v0.2.0
type DashboardFormat string
DashboardFormat controls value formatting in the browser.
const ( // DashboardFormatNumber renders a regular decimal number. DashboardFormatNumber DashboardFormat = "number" // DashboardFormatBytes renders a byte count with a binary size suffix. DashboardFormatBytes DashboardFormat = "bytes" // DashboardFormatPercent renders a value on the 0–100 percent scale. DashboardFormatPercent DashboardFormat = "percent" // DashboardFormatDuration renders a duration supplied in nanoseconds. DashboardFormatDuration DashboardFormat = "duration" )
type DashboardMetric ¶ added in v0.2.0
type DashboardMetric struct {
ID string
Title string
Description string
Unit string
Format DashboardFormat
Mode DashboardMetricMode
Sparkline bool
Color string
Value DashboardValueFunc
}
DashboardMetric configures a single custom metric card. Sparkline can be false when the card should contain only the current value.
type DashboardMetricMode ¶ added in v0.2.0
type DashboardMetricMode string
DashboardMetricMode describes how metric samples are interpreted.
const ( // DashboardMetricValue renders the current sample as-is. DashboardMetricValue DashboardMetricMode = "value" // DashboardMetricRate treats samples as a monotonically increasing counter // and renders its change per second. DashboardMetricRate DashboardMetricMode = "rate" )
type DashboardMetricSnapshot ¶ added in v0.2.0
type DashboardMetricSnapshot struct {
Value float64 `json:"value"`
Unit string `json:"unit,omitempty"`
Format DashboardFormat `json:"format"`
Mode DashboardMetricMode `json:"mode"`
Sparkline bool `json:"sparkline"`
Color string `json:"color,omitempty"`
Error string `json:"error,omitempty"`
}
DashboardMetricSnapshot contains the latest sample for a metric card.
type DashboardOption ¶ added in v0.2.0
type DashboardOption func(*dashboardConfig)
DashboardOption configures one dashboard widget.
func WithCPU ¶ added in v0.2.0
func WithCPU() DashboardOption
WithCPU adds the built-in process CPU card.
func WithCacheHitRate ¶ added in v0.2.0
func WithCacheHitRate() DashboardOption
WithCacheHitRate adds the built-in cache hit rate card.
func WithCounterGrid ¶ added in v0.2.0
func WithCounterGrid(grid DashboardCounterGrid) DashboardOption
WithCounterGrid adds a grid of counters without sparklines.
func WithCustomChart ¶ added in v0.2.0
func WithCustomChart(chart DashboardChart) DashboardOption
WithCustomChart adds a custom multi-series time chart.
func WithCustomMetric ¶ added in v0.2.0
func WithCustomMetric(metric DashboardMetric) DashboardOption
WithCustomMetric adds a custom metric card. Rate mode expects Value to return a cumulative counter; the UI derives its per-second change.
func WithEventMix ¶ added in v0.2.0
func WithEventMix() DashboardOption
WithEventMix adds the built-in event distribution panel.
func WithGoMemory ¶ added in v0.2.0
func WithGoMemory() DashboardOption
WithGoMemory adds the built-in Go memory card.
func WithGoroutines ¶ added in v0.2.0
func WithGoroutines() DashboardOption
WithGoroutines adds the built-in goroutine count card.
func WithQueries ¶ added in v0.2.0
func WithQueries() DashboardOption
WithQueries adds the built-in recorded query throughput card.
func WithQueueHealth ¶ added in v0.2.0
func WithQueueHealth() DashboardOption
WithQueueHealth adds the built-in queue health panel.
func WithRequests ¶ added in v0.2.0
func WithRequests() DashboardOption
WithRequests adds the built-in recorded request throughput card.
func WithSlowestOperations ¶ added in v0.2.0
func WithSlowestOperations() DashboardOption
WithSlowestOperations adds the built-in slow operations panel.
type DashboardSeries ¶ added in v0.2.0
type DashboardSeries struct {
ID string
Label string
Color string
Value DashboardValueFunc
}
DashboardSeries configures one line in a custom chart.
type DashboardSeriesSnapshot ¶ added in v0.2.0
type DashboardSeriesSnapshot struct {
ID string `json:"id"`
Label string `json:"label"`
Color string `json:"color,omitempty"`
Value float64 `json:"value"`
Error string `json:"error,omitempty"`
}
DashboardSeriesSnapshot contains the latest sample for one chart series.
type DashboardSnapshot ¶ added in v0.2.0
type DashboardSnapshot struct {
RecordedAt time.Time `json:"recorded_at"`
Widgets []DashboardWidgetSnapshot `json:"widgets"`
}
DashboardSnapshot contains one sampled dashboard configuration and its custom values.
type DashboardValueFunc ¶ added in v0.2.0
DashboardValueFunc returns the current value for a custom dashboard metric. Implementations should honor context cancellation and return quickly.
type DashboardWidgetSnapshot ¶ added in v0.2.0
type DashboardWidgetSnapshot struct {
ID string `json:"id"`
Kind string `json:"kind"`
Builtin string `json:"builtin,omitempty"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Span int `json:"span"`
Unit string `json:"unit,omitempty"`
Format DashboardFormat `json:"format,omitempty"`
Metric *DashboardMetricSnapshot `json:"metric,omitempty"`
Series []DashboardSeriesSnapshot `json:"series,omitempty"`
Counters []DashboardCounterSnapshot `json:"counters,omitempty"`
}
DashboardWidgetSnapshot is the browser-facing representation of one widget.
type Email ¶
type Email struct {
Meta
Transport string `json:"transport,omitempty"`
From Address `json:"from"`
To []Address `json:"to,omitempty"`
CC []Address `json:"cc,omitempty"`
BCC []Address `json:"bcc,omitempty"`
Subject string `json:"subject,omitempty"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
Status string `json:"status,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
}
Email describes an outgoing email delivery attempt.
type Entry ¶
type Entry struct {
Cursor uint64 `json:"cursor"`
ID string `json:"id"`
Kind Kind `json:"kind"`
RequestID string `json:"request_id,omitempty"`
ParentID string `json:"parent_id,omitempty"`
OriginRequestID string `json:"origin_request_id,omitempty"`
Process string `json:"process,omitempty"`
Instance string `json:"instance,omitempty"`
StartedAt time.Time `json:"started_at"`
RecordedAt time.Time `json:"recorded_at"`
DurationNS int64 `json:"duration_ns,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
Data json.RawMessage `json:"data"`
}
Entry is the normalized envelope returned by the profiler API and storage implementations. Data contains the JSON form associated with Kind.
type EntryStorage ¶ added in v0.4.0
type EntryStorage interface {
// Name identifies the backend in profiler storage statistics.
Name() string
// Load restores entries in ascending cursor order and the last cursor.
Load(context.Context) ([]Entry, uint64, error)
// Put inserts or replaces an entry and persists the latest cursor.
Put(context.Context, Entry, uint64) error
// Delete removes an entry evicted from the bounded window.
Delete(context.Context, string) error
// Clear removes all entries while preserving the supplied cursor.
Clear(context.Context, uint64) error
// Close releases resources held by the backend.
Close() error
}
EntryStorage persists the bounded event window outside the core package. Calls are serialized. Implementations must preserve the supplied monotonic cursor across restarts. Once selected by WithStorage, the active storage is owned and closed by Profiler.Close.
type Event ¶
type Event struct {
Meta
Kind string `json:"kind"`
Name string `json:"name"`
Status string `json:"status,omitempty"`
Summary string `json:"summary,omitempty"`
Fields map[string]any `json:"fields,omitempty"`
Error string `json:"error,omitempty"`
}
Event describes a custom domain or application event.
type EventResult ¶ added in v0.3.0
EventResult supplies values that are known only after an operation finishes. Empty values preserve those already set on the Event passed to StartEvent.
type EventSpan ¶ added in v0.3.0
type EventSpan struct {
// contains filtered or unexported fields
}
EventSpan measures a custom application operation and emits one Event when it is finished. Finish and FinishResult are safe to call more than once; only the first call records the event.
func StartEvent ¶ added in v0.3.0
StartEvent starts a custom event using the default profiler. The returned span still measures elapsed time when no profiler is active.
func (*EventSpan) Context ¶ added in v0.3.0
Context returns the operation context. Nested context-aware profilers inherit this event's ID as ParentID. When recording is disabled, it returns the original context without adding profiling metadata.
func (*EventSpan) Finish ¶ added in v0.3.0
func (s *EventSpan) Finish(err error) Measurement
Finish completes the operation. Errors are recorded on the Event and make its default status "failed"; successful events default to "succeeded".
func (*EventSpan) FinishResult ¶ added in v0.3.0
func (s *EventSpan) FinishResult(result EventResult) Measurement
FinishResult completes the operation with fields or presentation values that were not known when it started.
type Exception ¶
type Exception struct {
Meta
Type string `json:"type,omitempty"`
Message string `json:"message"`
Stack string `json:"stack,omitempty"`
}
Exception describes a captured error or recovered panic with an optional stack.
func PanicException ¶ added in v0.2.0
PanicException converts a recovered panic value into an exception event. Call it from the deferred function that recovered the panic so the stack still describes the failing goroutine.
type Finding ¶ added in v0.2.0
type Finding struct {
Code FindingCode `json:"code"`
Severity FindingSeverity `json:"severity"`
Title string `json:"title"`
Detail string `json:"detail,omitempty"`
Suggestion string `json:"suggestion,omitempty"`
EntryID string `json:"entry_id,omitempty"`
RelatedEntryIDs []string `json:"related_entry_ids,omitempty"`
}
Finding is an actionable conclusion produced from a recorded execution. EntryID points to the most useful related entry to open in the viewer.
type FindingCode ¶ added in v0.2.0
type FindingCode string
FindingCode identifies a stable class of automatic request finding.
const ( // FindingPossibleNPlusOne reports repeated structurally equivalent queries. FindingPossibleNPlusOne FindingCode = "possible_n_plus_one" // FindingSQLDominatesRequest reports requests that spend most of their time in SQL. FindingSQLDominatesRequest FindingCode = "sql_dominates_request" // FindingSQLDominatesSchedule reports schedules that spend most of their time in SQL. FindingSQLDominatesSchedule FindingCode = "sql_dominates_schedule" // FindingSQLDominatesCallable reports callables that spend most of their time in SQL. FindingSQLDominatesCallable FindingCode = "sql_dominates_callable" // FindingSQLDominatesTask reports tasks that spend most of their time in SQL. FindingSQLDominatesTask FindingCode = "sql_dominates_task" // FindingSequentialHTTPCalls reports outbound calls that appear to run serially. FindingSequentialHTTPCalls FindingCode = "sequential_http_calls" // FindingCacheMissQueryBurst reports repeated cache misses followed by queries. FindingCacheMissQueryBurst FindingCode = "cache_miss_query_burst" // FindingSlowMiddleware reports middleware above the built-in duration threshold. FindingSlowMiddleware FindingCode = "slow_middleware" // FindingSlowRequest reports requests above the built-in duration threshold. FindingSlowRequest FindingCode = "slow_request" // FindingSlowSchedule reports schedule executions above the built-in duration threshold. FindingSlowSchedule FindingCode = "slow_schedule" // FindingSlowCallable reports callable executions above the built-in duration threshold. FindingSlowCallable FindingCode = "slow_callable" // FindingSlowTask reports tasks above the built-in duration threshold. FindingSlowTask FindingCode = "slow_task" // FindingSlowQuery reports queries above the built-in duration threshold. FindingSlowQuery FindingCode = "slow_query" // FindingSlowHTTPCall reports outbound calls above the built-in duration threshold. FindingSlowHTTPCall FindingCode = "slow_http_call" // FindingSlowEvent reports measured custom events above the built-in duration threshold. FindingSlowEvent FindingCode = "slow_event" // FindingExecutionBottleneck reports the child operation dominating an execution. FindingExecutionBottleneck FindingCode = "execution_bottleneck" // FindingQueryPlanIssue reports a normalized concern found in a stored EXPLAIN plan. FindingQueryPlanIssue FindingCode = "query_plan_issue" // FindingFailedOperation reports a related operation carrying an error or failed status. FindingFailedOperation FindingCode = "failed_operation" // FindingHighCacheMissRate reports request timelines dominated by cache misses. FindingHighCacheMissRate FindingCode = "high_cache_miss_rate" )
type FindingSeverity ¶ added in v0.2.0
type FindingSeverity string
FindingSeverity describes how strongly a finding should be surfaced.
const ( // FindingSeverityInfo marks an informational optimization opportunity. FindingSeverityInfo FindingSeverity = "info" // FindingSeverityWarning marks a likely performance or reliability issue. FindingSeverityWarning FindingSeverity = "warning" // FindingSeverityDanger marks a failed or especially costly operation. FindingSeverityDanger FindingSeverity = "danger" )
type HTTPCall ¶
type HTTPCall struct {
Meta
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status,omitempty"`
Request HTTPMessage `json:"request,omitempty"`
Response HTTPMessage `json:"response,omitempty"`
ResponseSize int64 `json:"response_size,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
}
HTTPCall describes an outbound HTTP exchange.
type HTTPMessage ¶
type HTTPMessage struct {
Headers map[string][]string `json:"headers,omitempty"`
ContentType string `json:"content_type,omitempty"`
Body string `json:"body,omitempty"`
Size int64 `json:"size,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
HTTPMessage is a size-aware snapshot of HTTP headers and an optional body. Truncated reports whether Body was shortened by the configured body limit.
type Integration ¶
type Integration[T any] interface { // Name returns the stable cache namespace for this integration. Name() string // Profile instruments value using the supplied profiler scope. Profile(Scope, T) T }
Integration describes an adapter that instruments values of type T. Name scopes cached wrappers; Profile may return value unchanged when the underlying dependency cannot be wrapped.
type Job ¶
type Job struct {
Meta
Name string `json:"name"`
Queue string `json:"queue,omitempty"`
Connection string `json:"connection,omitempty"`
State string `json:"state,omitempty"`
Attempt int `json:"attempt,omitempty"`
MaxAttempts int `json:"max_attempts,omitempty"`
AvailableAt time.Time `json:"available_at,omitempty"`
Wait time.Duration `json:"wait_ns,omitempty"`
Arguments []Argument `json:"arguments,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
}
Job describes the enqueueing or execution state of a background job.
type Kind ¶
type Kind string
Kind identifies the schema stored in an Entry.
const ( // KindRequest identifies an inbound HTTP request. KindRequest Kind = "request" // KindQuery identifies a database query. KindQuery Kind = "query" // KindEmail identifies an outgoing email. KindEmail Kind = "email" // KindCache identifies a cache operation. KindCache Kind = "cache" // KindJob identifies a queued job. KindJob Kind = "job" // KindLog identifies a structured application log. KindLog Kind = "log" // KindHTTPCall identifies an outbound HTTP request. KindHTTPCall Kind = "http_call" // KindSchedule identifies a scheduled task execution. KindSchedule Kind = "schedule" // KindCallable identifies an explicitly invoked custom command execution. KindCallable Kind = "callable" // KindTask identifies a measured long-running application task. KindTask Kind = "task" // KindException identifies a captured error or panic. KindException Kind = "exception" // KindEvent identifies a custom application event. KindEvent Kind = "event" // KindMiddleware identifies one inbound middleware invocation. KindMiddleware Kind = "middleware" )
type Log ¶
type Log struct {
Meta
Level string `json:"level,omitempty"`
Message string `json:"message"`
Fields map[string]any `json:"fields,omitempty"`
Stack string `json:"stack,omitempty"`
}
Log describes one structured application log record.
type Measurement ¶ added in v0.3.0
Measurement describes the observed result of one measured operation. It is returned even when profiling is disabled, so callers may also use the duration and failure state for their own metrics.
func Measure ¶ added in v0.3.0
Measure runs fn as a custom event using the default profiler. The context passed to fn correlates nested profiler entries with the event.
func MeasureTask ¶ added in v0.5.0
MeasureTask runs fn as a standalone Task using the default profiler.
func MeasureValue ¶ added in v0.3.0
func MeasureValue[T any](ctx context.Context, event Event, fn func(context.Context) (T, error)) (T, Measurement)
MeasureValue runs a value-returning function as a custom event using the default profiler.
func MeasureValueWith ¶ added in v0.3.0
func MeasureValueWith[T any](profiler *Profiler, ctx context.Context, event Event, fn func(context.Context) (T, error)) (value T, measurement Measurement)
MeasureValueWith runs a value-returning function as a custom event using an explicit profiler. It is a function rather than a method because Go methods cannot declare type parameters.
func (Measurement) Failed ¶ added in v0.3.0
func (m Measurement) Failed() bool
Failed reports whether the measured function returned an error.
type Meta ¶
type Meta struct {
ID string `json:"id,omitempty"`
RequestID string `json:"request_id,omitempty"`
ParentID string `json:"parent_id,omitempty"`
OriginRequestID string `json:"origin_request_id,omitempty"`
Process string `json:"process,omitempty"`
Instance string `json:"instance,omitempty"`
StartedAt time.Time `json:"started_at,omitempty"`
Duration time.Duration `json:"duration_ns,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}
Meta contains correlation, timing, process, and tag data shared by all profiler entities.
type Middleware ¶ added in v0.2.0
type Middleware struct {
Meta
Name string `json:"name"`
State string `json:"state,omitempty"`
WorkDuration *time.Duration `json:"work_duration_ns,omitempty"`
WorkSpans []MiddlewareWorkSpan `json:"work_spans,omitempty"`
Error string `json:"error,omitempty"`
}
Middleware describes one named HTTP middleware invocation. Duration is the complete invocation span, including downstream handlers. WorkDuration is the measured time spent by the middleware itself before, between, and after calls to the downstream handler. Operations started by the middleware, such as SQL queries and HTTP calls, remain part of WorkDuration.
type MiddlewareWorkSpan ¶ added in v0.6.0
type MiddlewareWorkSpan struct {
Offset time.Duration `json:"offset_ns,omitempty"`
Duration time.Duration `json:"duration_ns"`
}
MiddlewareWorkSpan identifies one contiguous interval in which middleware code, rather than its downstream handler, was executing.
type Option ¶
type Option func(*config)
Option configures a Profiler during construction.
func Dashboard ¶ added in v0.2.0
func Dashboard(options ...DashboardOption) Option
Dashboard replaces the default dashboard with the supplied widgets.
func WithAllowedOrigins ¶
WithAllowedOrigins permits the listed browser origins to access profiler endpoints. Blank origins are ignored.
func WithBasePath ¶
WithBasePath changes the URL prefix used by the dashboard and JSON API. Empty paths and "/" leave the default /debug/webpprof prefix unchanged.
func WithBodyLimit ¶
WithBodyLimit limits captured HTTP request and response bodies. A zero limit disables body capture; negative values leave the default unchanged.
func WithBrowserSession ¶ added in v0.2.0
WithBrowserSession captures only requests marked with session in either the X-Webpprof-Session header or the webpprof_capture cookie.
func WithCallsiteKinds ¶ added in v0.2.0
WithCallsiteKinds replaces the set of entity kinds whose Go callsites are captured automatically. Passing no kinds disables automatic capture. The supported kinds are Query, Cache, Email, Job, HTTPCall, Schedule, Callable, and Task.
func WithDashboardTimeout ¶ added in v0.2.0
WithDashboardTimeout limits how long one dashboard snapshot may spend collecting values from custom metric callbacks.
func WithDisabledKinds ¶ added in v0.2.0
WithDisabledKinds prevents the listed entity kinds from being recorded.
func WithExcludedRequests ¶
WithExcludedRequests skips matching requests. Patterns may be paths, glob paths, prefix patterns ending in /*, or "METHOD path" pairs.
func WithHTTPStatusAtLeast ¶ added in v0.2.0
WithHTTPStatusAtLeast retains requests whose final status is at least status.
func WithHTTPStatusCodes ¶ added in v0.2.0
WithHTTPStatusCodes retains requests whose final status equals one of codes.
func WithMaxBytes ¶
WithMaxBytes bounds the approximate encoded size of entries kept in memory. Non-positive values leave the default limit unchanged.
func WithMaxEvents ¶
WithMaxEvents bounds the number of entries kept in memory. Non-positive values leave the default limit unchanged.
func WithMinRequestDuration ¶ added in v0.2.0
WithMinRequestDuration retains requests that took at least duration.
func WithNextRequests ¶ added in v0.2.0
WithNextRequests limits capture to the next count requests that pass early request filters and sampling. A zero or negative count captures none.
func WithQueryCallsite ¶ added in v0.2.0
WithQueryCallsite controls automatic Go stack capture for queries. It is enabled by default; disable it when the allocation overhead is undesirable. Deprecated: use WithCallsiteKinds to select all entity kinds whose callsites should be captured. This option remains available for backward compatibility.
func WithQueueStatsTimeout ¶
WithQueueStatsTimeout limits collection time for registered queue metrics. Non-positive values leave the default timeout unchanged.
func WithRequestFilter ¶
func WithRequestFilter(filter RequestFilter) Option
WithRequestFilter appends a capture predicate. All configured predicates must return true for a request to be recorded; nil predicates are ignored.
func WithRequestRetentionFilter ¶ added in v0.2.0
func WithRequestRetentionFilter(filter RequestRetentionFilter) Option
WithRequestRetentionFilter adds a predicate evaluated after the request has completed. Multiple retention filters are combined with AND.
func WithRequestSampleRate ¶ added in v0.2.0
WithRequestSampleRate records approximately the given fraction of incoming HTTP requests. Values are clamped to the inclusive range 0..1.
func WithRequestTags ¶ added in v0.2.0
WithRequestTags retains requests containing every configured tag/value pair.
func WithRetention ¶
WithRetention sets how long recorded entries remain available. Non-positive values leave the default retention unchanged.
func WithSecureCookie ¶
WithSecureCookie controls the Secure attribute of the dashboard session cookie. Enable it when the profiler is served over HTTPS.
func WithSidebarKinds ¶ added in v0.5.0
WithSidebarKinds replaces the ordered entity sections shown in the viewer sidebar. Dashboard remains first and All Events remains last. Passing no kinds hides every entity-specific section without disabling capture.
func WithSourceLink ¶ added in v0.2.0
func WithSourceLink(sourceLink SourceLinkFunc) Option
WithSourceLink makes captured Go frames clickable in the viewer.
func WithStorage ¶ added in v0.4.0
func WithStorage(storage EntryStorage) Option
WithStorage uses an optional external storage implementation. The storage is replayed at startup, pruned with the in-memory retention limits, and closed with the profiler. When multiple storage options are supplied, the last one wins. Pass nil to restore in-memory-only behavior.
func WithStoragePath ¶ added in v0.2.0
WithStoragePath persists captured entries in an append-only journal. The journal is replayed when the profiler starts and compacted automatically. Leave path empty to keep the default in-memory-only behavior.
func WithStreamBuffer ¶
WithStreamBuffer sets the per-subscriber live-event buffer size. Non-positive values leave the default size unchanged.
func WithToken ¶
WithToken protects the dashboard and API with the supplied access token. Start requires either a non-empty token or WithUnsafeUnauthenticatedAccess.
func WithUnsafeUnauthenticatedAccess ¶ added in v0.4.0
func WithUnsafeUnauthenticatedAccess() Option
WithUnsafeUnauthenticatedAccess exposes captured profiler data without a token. This should only be used on trusted local or otherwise isolated transports; remote access should use WithToken and additional network-level controls.
type Profiler ¶
type Profiler struct {
// contains filtered or unexported fields
}
Profiler records bounded diagnostic entries and serves the dashboard and API. A process has at most one active default Profiler; call Close or Shutdown to release it before constructing another.
func Default ¶
func Default() *Profiler
Default returns the active process-wide profiler, or nil when profiling is not initialized.
func New ¶
New creates the process-wide profiler and mounts its handlers on router. It returns the existing default profiler when already initialized and panics if router is nil on first initialization.
func NewIf ¶
NewIf calls New only when enabled. It is useful for environment-controlled setup and returns nil when disabled.
func Start ¶
Start runs the profiler dashboard on a dedicated HTTP server. The address may use port 0 for automatic allocation. Authentication must be configured with WithToken or explicitly disabled with WithUnsafeUnauthenticatedAccess.
func (*Profiler) AnalyzeCallable ¶ added in v0.5.0
func (p *Profiler) AnalyzeCallable(callableID string) (CallableAnalysis, bool)
AnalyzeCallable analyzes the complete ParentID hierarchy for a Callable. It returns false when callableID does not identify a retained Callable entry.
func (*Profiler) AnalyzeRequest ¶ added in v0.2.0
func (p *Profiler) AnalyzeRequest(requestID string) (RequestAnalysis, bool)
AnalyzeRequest analyzes the complete stored timeline for a request. It returns false when requestID does not identify a retained Request entry.
func (*Profiler) AnalyzeSchedule ¶ added in v0.5.0
func (p *Profiler) AnalyzeSchedule(scheduleID string) (ScheduleAnalysis, bool)
AnalyzeSchedule analyzes the complete ParentID hierarchy for a Schedule. It returns false when scheduleID does not identify a retained Schedule entry.
func (*Profiler) AnalyzeTask ¶ added in v0.5.0
func (p *Profiler) AnalyzeTask(taskID string) (TaskAnalysis, bool)
AnalyzeTask analyzes the complete ParentID hierarchy for a Task. It returns false when taskID does not identify a retained Task entry.
func (*Profiler) BasePath ¶
BasePath returns the URL prefix under which dashboard handlers are mounted.
func (*Profiler) BeginRequest ¶
func (p *Profiler) BeginRequest(request Request) *RequestCapture
BeginRequest starts a request capture bound to this profiler.
func (*Profiler) BodyLimit ¶
BodyLimit returns the maximum number of request or response body bytes captured by HTTP integrations.
func (*Profiler) CaptureCallsite ¶ added in v0.2.0
func (p *Profiler) CaptureCallsite(kind Kind) []SourceFrame
CaptureCallsite returns a stack only when automatic capture is enabled for kind on this profiler.
func (*Profiler) CaptureQueryCallsite ¶ added in v0.2.0
func (p *Profiler) CaptureQueryCallsite() []SourceFrame
CaptureQueryCallsite returns a query stack when query capture is enabled.
func (*Profiler) Close ¶
Close immediately stops an owned server, closes storage, and clears the default profiler. It is safe to call repeatedly; a nil receiver is a no-op.
func (*Profiler) DashboardSnapshot ¶ added in v0.2.0
func (p *Profiler) DashboardSnapshot(ctx context.Context) DashboardSnapshot
DashboardSnapshot samples every configured custom dashboard value.
func (*Profiler) LogCache ¶
LogCache records a cache operation and captures a callsite when configured.
func (*Profiler) LogCacheContext ¶
LogCacheContext records a cache operation with this profiler and correlation inherited from ctx.
func (*Profiler) LogCallable ¶ added in v0.5.0
LogCallable records an explicitly invoked custom command and captures a callsite when configured.
func (*Profiler) LogCallableContext ¶ added in v0.5.0
LogCallableContext records an explicitly invoked command with this profiler. Request and parent correlation are removed because Callable is a root entity.
func (*Profiler) LogEmail ¶
LogEmail records an outgoing email and captures a callsite when configured.
func (*Profiler) LogEmailContext ¶
LogEmailContext records an email with this profiler and correlation inherited from ctx.
func (*Profiler) LogEventContext ¶
LogEventContext records a custom event with this profiler and correlation inherited from ctx.
func (*Profiler) LogException ¶
LogException records an application error or recovered panic.
func (*Profiler) LogExceptionContext ¶
LogExceptionContext records an exception with this profiler and correlation inherited from ctx.
func (*Profiler) LogHTTPCall ¶
LogHTTPCall records an outbound HTTP call and captures a callsite when configured.
func (*Profiler) LogHTTPCallContext ¶
LogHTTPCallContext records an outbound HTTP call with this profiler and correlation inherited from ctx.
func (*Profiler) LogJobContext ¶
LogJobContext records a job with this profiler and correlation inherited from ctx.
func (*Profiler) LogLogContext ¶
LogLogContext records a structured log with this profiler and correlation inherited from ctx.
func (*Profiler) LogMiddleware ¶ added in v0.2.0
func (p *Profiler) LogMiddleware(middleware Middleware)
LogMiddleware records a standalone or explicitly correlated middleware invocation.
func (*Profiler) LogMiddlewareContext ¶ added in v0.2.0
func (p *Profiler) LogMiddlewareContext(ctx context.Context, middleware Middleware)
LogMiddlewareContext records middleware with inherited context tags and request correlation.
func (*Profiler) LogQuery ¶
LogQuery records a database query and captures a callsite when configured.
Example ¶
ExampleProfiler_LogQuery demonstrates manual SQL instrumentation.
package main
import (
"fmt"
"net/http"
"time"
"github.com/levskiy0/webpprof"
)
func main() {
mux := http.NewServeMux()
profiler := webpprof.New(mux, webpprof.WithUnsafeUnauthenticatedAccess())
defer profiler.Close()
startedAt := time.Now()
profiler.LogQuery(webpprof.Query{
Meta: webpprof.Meta{
StartedAt: startedAt,
Duration: 3 * time.Millisecond,
},
Driver: "postgres",
SQL: "select id, email from users where id = $1",
})
fmt.Println(profiler.Enabled())
}
Output: true
func (*Profiler) LogQueryContext ¶
LogQueryContext records a query with this profiler and inherits tags, parent entry, and request correlation from ctx.
func (*Profiler) LogRequest ¶
LogRequest records a completed request and stores its related entities as individually correlated entries. Retention filters may discard the request.
func (*Profiler) LogSchedule ¶
LogSchedule records a scheduled task and captures a callsite when configured.
func (*Profiler) LogScheduleContext ¶
LogScheduleContext records a scheduled task with this profiler. Request and parent correlation are removed because Schedule is a root entity.
func (*Profiler) LogTask ¶ added in v0.5.0
LogTask records a measured application task and captures a callsite when configured.
func (*Profiler) LogTaskContext ¶ added in v0.5.0
LogTaskContext records a measured task with this profiler. Request and parent correlation are removed because Task is a root entity.
func (*Profiler) Measure ¶ added in v0.3.0
func (p *Profiler) Measure(ctx context.Context, event Event, fn func(context.Context) error) Measurement
Measure runs fn as a custom event using p.
func (*Profiler) MeasureTask ¶ added in v0.5.0
func (p *Profiler) MeasureTask(ctx context.Context, task Task, fn func(context.Context) error) Measurement
MeasureTask runs fn as a standalone Task using p.
func (*Profiler) QueueStats ¶
func (p *Profiler) QueueStats(ctx context.Context) QueueStatsResponse
QueueStats collects registered sources in name order under the configured aggregate timeout. Source errors are embedded in the corresponding snapshot.
func (*Profiler) RegisterQueueStats ¶
func (p *Profiler) RegisterQueueStats(source QueueStatsSource, names ...string) QueueStatsSource
RegisterQueueStats registers source on this profiler and returns it. A later source with the same name replaces the earlier registration.
func (*Profiler) RuntimeStats ¶
func (p *Profiler) RuntimeStats() RuntimeStats
RuntimeStats returns a point-in-time snapshot of selected runtime/metrics values and profiler uptime. A nil profiler returns a zero snapshot.
func (*Profiler) ShouldCaptureRequest ¶
ShouldCaptureRequest applies this profiler's exclusions, filters, sampling rate, and optional request limit. A successful call consumes one configured request-limit slot.
func (*Profiler) Shutdown ¶
Shutdown gracefully stops this profiler's owned server, closes storage, and clears the default profiler. A nil receiver is a no-op.
func (*Profiler) StartEvent ¶ added in v0.3.0
StartEvent starts a custom event using p. Pass span.Context() to nested work so its profiler entries use this event as their parent.
type Query ¶
type Query struct {
Meta
Connection string `json:"connection,omitempty"`
Driver string `json:"driver,omitempty"`
Database string `json:"database,omitempty"`
Operation string `json:"operation,omitempty"`
SQL string `json:"sql"`
RowsAffected *int64 `json:"rows_affected,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Plan *QueryPlan `json:"plan,omitempty"`
Error string `json:"error,omitempty"`
}
Query describes a database operation, including its SQL, timing, result, and optional source callsite or EXPLAIN plan.
type QueryPlan ¶ added in v0.2.0
type QueryPlan struct {
Command string `json:"command,omitempty"`
Format string `json:"format,omitempty"`
Text string `json:"text,omitempty"`
Duration time.Duration `json:"duration_ns,omitempty"`
Issues []QueryPlanIssue `json:"issues,omitempty"`
Error string `json:"error,omitempty"`
}
QueryPlan contains a non-executing SQL EXPLAIN result. Duration measures the plan lookup itself and is intentionally separate from Query.Duration.
type QueryPlanIssue ¶ added in v0.5.0
type QueryPlanIssue struct {
Code QueryPlanIssueCode `json:"code"`
Relation string `json:"relation,omitempty"`
EstimatedRows int64 `json:"estimated_rows,omitempty"`
Detail string `json:"detail,omitempty"`
}
QueryPlanIssue is a conservative, driver-independent interpretation of one plain EXPLAIN plan line. Detail retains the supporting plan fragment.
func DetectQueryPlanIssues ¶ added in v0.5.0
func DetectQueryPlanIssues(driverName, planText string) []QueryPlanIssue
DetectQueryPlanIssues normalizes conservative performance signals from a plain-text EXPLAIN plan. It never executes the statement and returns no issue for plan shapes it cannot recognize safely.
type QueryPlanIssueCode ¶ added in v0.5.0
type QueryPlanIssueCode string
QueryPlanIssueCode identifies a normalized concern found in a plain SQL EXPLAIN plan. Codes are stable across supported database drivers.
const ( // QueryPlanIssueFullScan reports a sequential or full table scan. QueryPlanIssueFullScan QueryPlanIssueCode = "full_scan" // QueryPlanIssueTemporarySort reports an explicit temporary sort or table. QueryPlanIssueTemporarySort QueryPlanIssueCode = "temporary_sort" // QueryPlanIssueLargeEstimate reports a large row estimate in a plan node. QueryPlanIssueLargeEstimate QueryPlanIssueCode = "large_estimate" )
type QuerySpan ¶
type QuerySpan struct {
// contains filtered or unexported fields
}
QuerySpan measures one database query and guarantees that it is logged at most once when finished.
func StartQuery ¶
StartQuery begins measuring query. Finish or FinishRows must be called to record it; a missing StartedAt timestamp is initialized automatically.
func (*QuerySpan) Finish ¶
Finish records the query without a rows-affected value. Repeated calls are ignored.
func (*QuerySpan) FinishRows ¶
FinishRows records the query with its rows-affected value. Repeated calls are ignored.
type QueueState ¶
type QueueState struct {
Name string `json:"name"`
WorkersActive int64 `json:"workers_active"`
WorkersTotal int64 `json:"workers_total"`
Processed uint64 `json:"processed"`
Succeeded uint64 `json:"succeeded"`
Failed uint64 `json:"failed"`
Pending int64 `json:"pending"`
}
QueueState contains worker and job counters for one named queue.
type QueueStats ¶
type QueueStats struct {
Source string `json:"source"`
RecordedAt time.Time `json:"recorded_at"`
StartedAt time.Time `json:"started_at,omitempty"`
WorkersActive int64 `json:"workers_active"`
WorkersTotal int64 `json:"workers_total"`
Processed uint64 `json:"processed"`
Succeeded uint64 `json:"succeeded"`
Failed uint64 `json:"failed"`
Pending int64 `json:"pending"`
Queues []QueueState `json:"queues"`
Error string `json:"error,omitempty"`
}
QueueStats contains aggregate worker and job counters from one registered queue source.
type QueueStatsResponse ¶
type QueueStatsResponse struct {
RecordedAt time.Time `json:"recorded_at"`
Sources []QueueStats `json:"sources"`
}
QueueStatsResponse combines snapshots from every registered queue source.
type QueueStatsSource ¶
type QueueStatsSource interface {
// QueueStats collects the current queue snapshot.
QueueStats(context.Context) (QueueStats, error)
}
QueueStatsSource provides a snapshot of one queue backend. Implementations should honor cancellation and deadlines from ctx.
func RegisterQueueStats ¶
func RegisterQueueStats(source QueueStatsSource, names ...string) QueueStatsSource
RegisterQueueStats registers source on the default profiler and returns it for convenient inline wrapping. The optional first non-blank name identifies it.
type QueueStatsSourceFunc ¶
type QueueStatsSourceFunc func(context.Context) (QueueStats, error)
QueueStatsSourceFunc adapts a function to QueueStatsSource.
func (QueueStatsSourceFunc) QueueStats ¶
func (f QueueStatsSourceFunc) QueueStats(ctx context.Context) (QueueStats, error)
QueueStats calls f with ctx.
type Request ¶
type Request struct {
Meta
Method string `json:"method"`
Path string `json:"path"`
Route string `json:"route,omitempty"`
Query string `json:"query,omitempty"`
Scheme string `json:"scheme,omitempty"`
Protocol string `json:"protocol,omitempty"`
Host string `json:"host,omitempty"`
RemoteIP string `json:"remote_ip,omitempty"`
Status int `json:"status"`
RequestSize int64 `json:"request_size,omitempty"`
ResponseSize int64 `json:"response_size,omitempty"`
Request HTTPMessage `json:"request,omitempty"`
Response HTTPMessage `json:"response,omitempty"`
Error string `json:"error,omitempty"`
Queries []Query `json:"queries,omitempty"`
Emails []Email `json:"emails,omitempty"`
Cache []Cache `json:"cache,omitempty"`
Jobs []Job `json:"jobs,omitempty"`
Logs []Log `json:"logs,omitempty"`
HTTPCalls []HTTPCall `json:"http_calls,omitempty"`
Schedules []Schedule `json:"schedules,omitempty"`
Exceptions []Exception `json:"exceptions,omitempty"`
Events []Event `json:"events,omitempty"`
Middlewares []Middleware `json:"middlewares,omitempty"`
}
Request describes an inbound HTTP exchange and may temporarily contain related entities before LogRequest stores them as individually linked entries.
type RequestAnalysis ¶ added in v0.2.0
type RequestAnalysis struct {
RequestID string `json:"request_id"`
RequestDurationNS int64 `json:"request_duration_ns"`
GeneratedAt time.Time `json:"generated_at"`
Findings []Finding `json:"findings"`
}
RequestAnalysis contains automatic findings for one captured HTTP request.
type RequestCapture ¶
type RequestCapture struct {
// contains filtered or unexported fields
}
RequestCapture buffers entities produced during one inbound request and logs the completed request exactly once.
func BeginRequest ¶
func BeginRequest(request Request) *RequestCapture
BeginRequest starts a request capture using the default profiler at Finish time. Missing IDs and start times are initialized automatically.
func RequestFromContext ¶
func RequestFromContext(ctx context.Context) *RequestCapture
RequestFromContext returns the request capture associated with ctx, if any.
func (*RequestCapture) AddTags ¶ added in v0.2.0
func (c *RequestCapture) AddTags(tags map[string]string)
AddTags adds or replaces tags on the captured request.
func (*RequestCapture) Finish ¶
func (c *RequestCapture) Finish(result RequestResult)
Finish records the request and its buffered entities. Only the first call has an effect; later calls are ignored.
func (*RequestCapture) ID ¶
func (c *RequestCapture) ID() string
ID returns the stable request identifier assigned to this capture.
func (*RequestCapture) LogCache ¶
func (c *RequestCapture) LogCache(cache Cache)
LogCache buffers a cache operation under this request until Finish.
func (*RequestCapture) LogEmail ¶
func (c *RequestCapture) LogEmail(email Email)
LogEmail buffers an email under this request until Finish.
func (*RequestCapture) LogEvent ¶
func (c *RequestCapture) LogEvent(event Event)
LogEvent buffers a custom event under this request until Finish.
func (*RequestCapture) LogException ¶
func (c *RequestCapture) LogException(exception Exception)
LogException buffers an exception under this request until Finish.
func (*RequestCapture) LogHTTPCall ¶
func (c *RequestCapture) LogHTTPCall(call HTTPCall)
LogHTTPCall buffers an outbound HTTP call under this request until Finish.
func (*RequestCapture) LogJob ¶
func (c *RequestCapture) LogJob(job Job)
LogJob buffers a job under this request until Finish.
func (*RequestCapture) LogLog ¶
func (c *RequestCapture) LogLog(log Log)
LogLog buffers a structured log under this request until Finish.
func (*RequestCapture) LogMiddleware ¶ added in v0.2.0
func (c *RequestCapture) LogMiddleware(middleware Middleware)
LogMiddleware buffers middleware under this request capture.
func (*RequestCapture) LogQuery ¶
func (c *RequestCapture) LogQuery(query Query)
LogQuery buffers a query under this request until Finish.
func (*RequestCapture) LogSchedule ¶
func (c *RequestCapture) LogSchedule(schedule Schedule)
LogSchedule buffers a scheduled task under this request until Finish.
func (*RequestCapture) SetRoute ¶ added in v0.2.0
func (c *RequestCapture) SetRoute(route string)
SetRoute updates the matched route pattern before the request is finished. Framework middleware can call it after routing has selected a handler.
type RequestFilter ¶
RequestFilter decides whether an incoming request should be captured. Returning false skips the request and all entities correlated with it.
func ExcludingRequests ¶
func ExcludingRequests(patterns ...string) RequestFilter
ExcludingRequests builds a reusable RequestFilter that rejects matching paths or "METHOD path" patterns.
Example ¶
ExampleExcludingRequests demonstrates reusable request capture rules.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/levskiy0/webpprof"
)
func main() {
filter := webpprof.ExcludingRequests("GET /health", "/assets/*")
health := httptest.NewRequest(http.MethodGet, "/health", nil)
postHealth := httptest.NewRequest(http.MethodPost, "/health", nil)
asset := httptest.NewRequest(http.MethodGet, "/assets/app.js", nil)
fmt.Println(filter(health), filter(postHealth), filter(asset))
}
Output: false true false
type RequestResult ¶
type RequestResult struct {
Status int
ResponseSize int64
Response HTTPMessage
Error string
}
RequestResult supplies response metadata when a RequestCapture is finished.
type RequestRetentionFilter ¶ added in v0.2.0
RequestRetentionFilter decides whether a completed request and all of its related entities should be persisted.
type Router ¶
Router is the minimal HTTP routing contract required to mount the profiler. Both http.ServeMux and routers exposing the same Handle method satisfy it.
type RuntimeStats ¶
type RuntimeStats struct {
RecordedAt time.Time `json:"recorded_at"`
UptimeNS int64 `json:"uptime_ns"`
CPUSeconds float64 `json:"cpu_seconds"`
CPUIdleSeconds float64 `json:"cpu_idle_seconds"`
MemoryBytes uint64 `json:"memory_bytes"`
HeapObjectsBytes uint64 `json:"heap_objects_bytes"`
HeapLiveBytes uint64 `json:"heap_live_bytes"`
Goroutines uint64 `json:"goroutines"`
GCCycles uint64 `json:"gc_cycles"`
GOMAXPROCS int `json:"gomaxprocs"`
}
RuntimeStats is a point-in-time snapshot of selected Go runtime metrics.
type Schedule ¶
type Schedule struct {
Meta
Name string `json:"name"`
State string `json:"state,omitempty"`
PlannedAt time.Time `json:"planned_at,omitempty"`
Payload any `json:"payload,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
Panic string `json:"panic,omitempty"`
}
Schedule describes one scheduled task invocation and its outcome.
type ScheduleAnalysis ¶ added in v0.5.0
type ScheduleAnalysis struct {
ScheduleID string `json:"schedule_id"`
ScheduleDurationNS int64 `json:"schedule_duration_ns"`
GeneratedAt time.Time `json:"generated_at"`
Findings []Finding `json:"findings"`
}
ScheduleAnalysis contains automatic findings for one captured Schedule execution.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope gives an integration access to the active profiler and a namespaced, concurrency-safe cache for reusing wrappers.
func (Scope) Load ¶
Load retrieves a value previously cached by this integration. Non-comparable keys are rejected and return no value.
func (Scope) LoadOrStore ¶
LoadOrStore returns an existing scoped value when present or stores value. The loaded result follows sync.Map semantics.
type SourceFrame ¶ added in v0.2.0
type SourceFrame struct {
Function string `json:"function,omitempty"`
File string `json:"file"`
Line int `json:"line"`
URL string `json:"url,omitempty"`
}
SourceFrame identifies one Go frame that led to a profiled operation. URL is optional and can point to an editor deep link such as vscode://file/....
func CaptureCallsite ¶ added in v0.2.0
func CaptureCallsite(kind Kind) []SourceFrame
CaptureCallsite returns the application stack that led to an operation. Integrations may call it before delegating to a dependency so the first frame points at application code rather than at the profiler wrapper.
func CaptureQueryCallsite ¶ added in v0.2.0
func CaptureQueryCallsite() []SourceFrame
CaptureQueryCallsite is kept as a compatibility alias for SQL integrations.
type SourceLinkFunc ¶ added in v0.2.0
type SourceLinkFunc func(SourceFrame) string
SourceLinkFunc converts a captured Go source frame into an editor or source browser URL. Return an empty string when a frame should not be linked.
type Stats ¶
type Stats struct {
Events int `json:"events"`
Bytes int64 `json:"bytes"`
DroppedEvents uint64 `json:"dropped_events"`
EvictedEvents uint64 `json:"evicted_events"`
Subscribers int `json:"subscribers"`
Cursor uint64 `json:"cursor"`
MaxEvents int `json:"max_events"`
MaxBytes int64 `json:"max_bytes"`
RetentionNS int64 `json:"retention_ns"`
Storage string `json:"storage"`
StorageError string `json:"storage_error,omitempty"`
BodyLimit int64 `json:"body_limit"`
SampleRate float64 `json:"request_sample_rate"`
DisabledKinds []Kind `json:"disabled_kinds,omitempty"`
SidebarKinds []Kind `json:"sidebar_kinds"`
}
Stats reports current profiler capacity, retention, and storage state.
type Task ¶ added in v0.5.0
type Task struct {
Meta
Name string `json:"name"`
State string `json:"state,omitempty"`
Fields map[string]any `json:"fields,omitempty"`
Callsite []SourceFrame `json:"callsite,omitempty"`
Error string `json:"error,omitempty"`
Panic string `json:"panic,omitempty"`
}
Task describes one measured long-running application operation.
type TaskAnalysis ¶ added in v0.5.0
type TaskAnalysis struct {
TaskID string `json:"task_id"`
TaskDurationNS int64 `json:"task_duration_ns"`
GeneratedAt time.Time `json:"generated_at"`
Findings []Finding `json:"findings"`
}
TaskAnalysis contains automatic findings for one captured Task execution.
type TaskResult ¶ added in v0.5.0
TaskResult supplies state and fields known only when a Task finishes.
type TaskSpan ¶ added in v0.5.0
type TaskSpan struct {
// contains filtered or unexported fields
}
TaskSpan measures one long-running application task. Finish and FinishResult are idempotent; only the first call records the Task.
func (*TaskSpan) Context ¶ added in v0.5.0
Context returns the Task execution context for nested profiler operations.
func (*TaskSpan) Finish ¶ added in v0.5.0
func (s *TaskSpan) Finish(err error) Measurement
Finish completes the Task and records a returned error.
func (*TaskSpan) FinishResult ¶ added in v0.5.0
func (s *TaskSpan) FinishResult(result TaskResult) Measurement
FinishResult completes the Task with state or fields known at completion.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client provides a read-only HTTP client for a running webpprof instance.
|
Package client provides a read-only HTTP client for a running webpprof instance. |
|
cmd
|
|
|
webpprof-mcp
module
|
|
|
internal
|
|
|
profiler
|
|
|
callable
Package callable wraps context-aware custom commands and records each call as an independent execution root.
|
Package callable wraps context-aware custom commands and records each call as an independent execution root. |
|
email
Package email instruments application-defined email senders without tying webpprof to a particular mail transport.
|
Package email instruments application-defined email senders without tying webpprof to a particular mail transport. |
|
http
Package http provides inbound net/http middleware and an outbound transport wrapper that correlate HTTP activity with webpprof request captures.
|
Package http provides inbound net/http middleware and an outbound transport wrapper that correlate HTTP activity with webpprof request captures. |
|
schedule
Package schedule wraps context-aware scheduled tasks and records their duration, success, and panics.
|
Package schedule wraps context-aware scheduled tasks and records their duration, success, and panics. |
|
slog
Package slog wraps a log/slog Handler and mirrors accepted records into webpprof while preserving the original handler chain.
|
Package slog wraps a log/slog Handler and mirrors accepted records into webpprof while preserving the original handler chain. |
|
sql
Package sql wraps database/sql drivers and connectors so queries are recorded without requiring changes to application query calls.
|
Package sql wraps database/sql drivers and connectors so queries are recorded without requiring changes to application query calls. |
|
asynq
module
|
|
|
bun
module
|
|
|
chi
module
|
|
|
echo
module
|
|
|
fiber
module
|
|
|
gin
module
|
|
|
gocache
module
|
|
|
gomail
module
|
|
|
goqueue
module
|
|
|
goredis
module
|
|
|
gorm
module
|
|
|
grpc
module
|
|
|
kafka
module
|
|
|
nats
module
|
|
|
otel
module
|
|
|
pgx
module
|
|
|
zap
module
|
|
|
zerolog
module
|
|
|
scripts
|
|
|
check-docs
command
Command check-docs verifies that public Go packages document their exported API.
|
Command check-docs verifies that public Go packages document their exported API. |
|
storage
|
|
|
sqlite
module
|
