webpprof

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 36 Imported by: 0

README

webpprof — a Telescope-like request profiler and debug toolbar for Go

Go Reference CI

webpprof is a Telescope-like request profiler and debug toolbar for Go (Golang) web applications. It shows everything one HTTP request did — SQL queries, cache operations, background jobs, logs, mail, outgoing HTTP calls, middleware, and panics — in one searchable local UI.

Early-stage: webpprof is pre-v1. Public APIs and persisted capture formats may change between minor releases, so pin a version and review the changelog before upgrading.

Use it to find why an endpoint is slow, inspect the SQL it executed, follow related operations through context.Context, and replay a captured HTTP request as cURL. webpprof runs inside the application and needs no external collector, Docker stack, or database.

webpprof is a development and diagnostic tool, not a long-term production APM. Captures are bounded and kept in memory by default, with optional local persistence for short investigations.

webpprof query details with a correlated request and highlighted SQL

Why webpprof?

Go already has excellent runtime profiling and observability tools. webpprof adds a request-centric view for application debugging:

  • Why is this HTTP endpoint slow?
  • Which SQL queries, cache operations, and outgoing calls did it execute?
  • Which logs, jobs, mail, and exceptions belong to it?
  • What happened before a panic or failed response?
  • Can an AI coding agent inspect the same captured timeline?

It complements pprof, tracing, and production APMs with a quick local Go request profiler, SQL query profiler, debug toolbar, and observability dashboard.

Features

  • Inspect method, route, status, duration, headers, bounded bodies, raw HTTP, and ready-to-run cURL for captured requests.
  • Correlate middleware, SQL, cache, jobs, logs, mail, outgoing HTTP, exceptions, and custom events through context.Context; inspect Schedule, Callable, and measured Task work as standalone execution roots.
  • Find possible N+1 queries, SQL-heavy requests, sequential HTTP calls, cache miss/query bursts, slow middleware, and direct operation failures.
  • Explore a request-wide waterfall with nesting, critical path, bottleneck, and operation-time breakdown.
  • Search and filter live events by entity, duration, status, time, and tags.
  • Profile net/http, Gin, Chi, Echo, Fiber, gRPC, pgx, GORM, Bun, database/sql, Redis, queues, messaging, logging, mail, and OpenTelemetry.
  • Let Codex, Claude, Cursor, and other MCP clients inspect the profiler through the separate read-only webpprof-mcp binary.

Measured capture overhead

The repository includes an end-to-end benchmark that marshals and redacts a custom event, records it into a full 10,000-entry store, and performs one FIFO eviction per operation. Results on Go 1.25.13, darwin/arm64, Apple M3 Pro:

Configuration Time/op Bytes/op Allocs/op
Event kind disabled 52 ns 224 B 1
In-memory, steady-state eviction 3.89 µs 4,162 B 51
JSONL journal, steady-state eviction 8.82 µs 5,204 B 60
SQLite, steady-state eviction 73.4 µs 5,790 B 88

Run both benchmark suites on deployment-like hardware:

go test . -run '^$' -bench BenchmarkProfilerOverhead -benchmem -count=6
go test ./storage/sqlite -run '^$' -bench BenchmarkProfilerSQLiteSteadyStateEviction -benchmem -count=6

The SQLite row includes synchronous eviction and write I/O. Run the relevant suite before enabling additional capture kinds in a hot path. These numbers are a reproducible reference, not a latency guarantee.

Getting started

Install the core module:

go get github.com/levskiy0/webpprof@latest

Start a private profiler server and wrap the application handler:

profiler, err := webpprof.Start(
    "127.0.0.1:6061",
    webpprof.WithToken(os.Getenv("WEBPPROF_TOKEN")),
    webpprof.WithExcludedRequests("GET /health", "GET *.js", "GET *.webp"),
)
if err != nil {
    return err
}
defer profiler.Shutdown(context.Background())

handler := webpprofhttp.MiddlewareWith(profiler, applicationHandler)

Pass the handler's context to database, cache, logger, queue, mail, and HTTP client operations. Their profilers use that context to attach events to the request:

if err := repository.Find(r.Context(), playerID); err != nil {
    return err
}
logger.InfoContext(r.Context(), "player loaded", "player_id", playerID)

Open http://127.0.0.1:6061/debug/webpprof/ and enter the token. Use webpprof.New(router, options...) instead when the application owns the HTTP server that serves the profiler UI.

Third-party integrations are independent nested Go modules, so installing Gin, pgx, or GORM support does not add unrelated SDKs to the application's module graph:

go get github.com/levskiy0/webpprof/profiler/gin@latest
go get github.com/levskiy0/webpprof/profiler/pgx@latest
go get github.com/levskiy0/webpprof/profiler/gorm@latest

See all integrations and setup examples.

Debug with AI agents over MCP

webpprof-mcp is a separate process. It reads a running profiler through its private HTTP API and exposes bounded, read-only MCP tools over stdio:

Codex / Claude / Cursor <-- MCP over stdio --> webpprof-mcp <-- HTTP --> Go application

Installing the Go library does not install the MCP executable. Install its independent module from any directory:

go install github.com/levskiy0/webpprof/cmd/webpprof-mcp@latest
webpprof-mcp --version

For a reproducible install, replace @latest with @v0.5.0. The executable is written to GOBIN, or GOPATH/bin when GOBIN is unset.

The MCP command is versioned independently. Its versions are published as cmd/webpprof-mcp/vX.Y.Z Go module tags through proxy.golang.org, without a separate GitHub Release. Use @latest or pin an exact command version.

Register it in Codex:

codex mcp add webpprof \
  --env WEBPPROF_TOKEN="$WEBPPROF_TOKEN" \
  -- webpprof-mcp --url http://127.0.0.1:6061/debug/webpprof/

The server provides tools to check status, list and wait for requests, inspect automatic findings, and search related events. Payloads, values, arguments, and stacks are omitted unless explicitly requested; tools never replay requests, clear events, or mutate the application.

See MCP installation, client configuration, tools, and security.

Try it locally

Run the bundled application from the repository root:

go run ./example

Open http://127.0.0.1:3030/, generate a successful, failed, or panic request, then inspect it at http://127.0.0.1:3030/debug/webpprof/. The example is a real net/http application using database/sql, pure-Go SQLite, structured log/slog, SQL EXPLAIN, and SQLite-backed profiler storage. Its composition root shows the complete integration in one place: wrap the HTTP handler, SQL driver, and slog handler once. Its ordinary handlers also use the optional Measure helper to create service-level spans while SQL and logs remain automatic. The clearly marked /api/manual/* routes contain the custom integration and synthetic diagnostics. See example/README.md for the annotated wiring, automatic behavior, routes, and configuration.

What is recorded

Entity Automatic profilers Examples of recorded data
HTTP request http, Gin, Chi, Echo, Fiber, gRPC Route, status, headers, bounded bodies, duration, error
Middleware http, Gin Name, state, total span, measured middleware work, error
SQL query Bun, GORM, pgx, database/sql, OTel SQL, connection, rows, duration, callsite, optional EXPLAIN
Cache go-cache, go-redis Store, operation, key, hit, TTL, duration, error
Job go-queue, Asynq Queue, state, attempts, bounded arguments, duration, error
Log slog, Zap, zerolog Level, message, structured fields, stack
Mail email, go-mail Transport, recipients, subject, state, duration, error
Outgoing call HTTP, gRPC Method, target, status, bounded payloads, duration, error
Messaging NATS, kafka-go Subject/topic, producer/consumer state, size, duration, error
Schedule schedule Name, planned time, state, duration, error or panic
Callable callable Custom command name, state, duration, payload/result, error or panic
Task core StartTask / MeasureTask Application operation name, state, fields, duration, error or panic
Exception/event HTTP recovery or manual API Type, message, stack, custom fields and tags

All entity types also have context-aware manual logging APIs. See the complete event and entity reference.

Use Task for a long-running application operation that is neither an incoming request, a scheduled callback, nor a callable command. It becomes an independent execution root; pass the callback context to dependencies so its queries, logs, cache operations, and outgoing calls appear in the same scope:

measurement := profiler.MeasureTask(ctx, webpprof.Task{
    Name:   "reports.players.generate",
    Fields: map[string]any{"format": "pdf"},
}, func(taskCtx context.Context) error {
    return reports.Generate(taskCtx)
})

return measurement.Err

Use StartTask and FinishResult when the lifecycle crosses function boundaries or result fields are only known at completion.

For application services and unsupported dependencies, measure a block without writing stopwatch/error boilerplate:

measurement := profiler.Measure(ctx, webpprof.Event{
    Kind: "service",
    Name: "players.refresh",
}, func(ctx context.Context) error {
    return players.Refresh(ctx) // nested profilers inherit this Event as parent
})

metrics.Record(measurement.Failed(), measurement.Duration)
return measurement.Err

MeasureValueWith covers (T, error) functions. StartEvent plus FinishResult provides a manual lifecycle for async wrappers or result-derived status and fields. All helpers use only the standard library, honor WithoutRecording, preserve panics after recording them, and are documented in writing a custom profiler.

Supported integrations

Core and standard-library profilers ship in the root module:

Package Integration point
profiler/http Incoming http.Handler, named middleware, and http.RoundTripper
profiler/sql driver.Connector or driver.Driver before sql.OpenDB
profiler/slog Standard slog.Handler
profiler/email Dependency-neutral mail Sender
profiler/schedule Scheduled func(context.Context) callbacks
profiler/callable Custom func(context.Context) error commands

Optional integrations are isolated modules:

Area Modules
HTTP and RPC Gin, Chi, Echo, Fiber, gRPC
SQL and ORM pgx, GORM, Bun
Cache go-cache, go-redis
Jobs go-queue, Asynq
Messaging NATS, kafka-go
Logging Zap, zerolog
Mail and tracing go-mail, OpenTelemetry

The application retains ownership of wrapped dependencies and closes them as usual. Use one profiler per operation path: stacking Bun, GORM, pgx, database/sql, or OTel instrumentation around the same query records duplicates.

See installation and recipes for every profiler and SQL callsites, EXPLAIN, and replay.

Execution correlation and findings

The request middleware stores a capture in context.Context. Context-aware profilers and Log*Context functions inherit the request ID, tags, and current parent operation:

flowchart LR
    A["Incoming request"] --> B["webpprof middleware"]
    B --> C["context.Context"]
    C --> D["SQL / cache / logs"]
    C --> E["jobs / mail / HTTP calls"]
    D --> F["Request timeline and findings"]
    E --> F

Automatic findings currently cover repeated query fingerprints, SQL wall-clock coverage, sequential safe HTTP calls, cache miss/query bursts, slow middleware, slow operations, and failed execution roots, jobs, mail, or HTTP calls. Schedule and Callable wrappers plus the Task lifecycle create independent roots and parent their nested work. Bottleneck analysis follows those parent links and prefers a nested operation when it explains most of an inclusive wrapper span. It also requires operation-specific absolute latency thresholds, so an otherwise fast operation is not labeled merely for being the longest.

See request correlation, tags, middleware timing, and finding rules.

Configuration and security

Captures default to at most 10,000 events or 64 MiB for 30 minutes, with a 64 KiB limit per HTTP body. Configure retention, byte limits, sampling, selective capture, redaction, disabled event kinds, and optional local storage at startup:

sqliteStorage, err := webpprofsqlite.Open(context.Background(), "./var/webpprof/events.db")
if err != nil {
    return err
}

profiler := webpprof.New(
    mux,
    webpprof.WithToken(os.Getenv("WEBPPROF_TOKEN")),
    webpprof.WithRetention(2*time.Hour),
    webpprof.WithMaxEvents(25_000),
    webpprof.WithMaxBytes(128<<20),
    webpprof.WithRequestSampleRate(0.25),
    webpprof.WithStorage(sqliteStorage),
)

SQLite is an independent optional module: go get github.com/levskiy0/webpprof/storage/sqlite@latest. Without a token, captured data and live updates stay unavailable. Local-only unauthenticated access requires the explicit webpprof.WithUnsafeUnauthenticatedAccess() option. Existing SQLite users should follow the migration example.

Keep the profiler on loopback or a private administrative network and always set a strong token outside source control. Captures can contain personal data, SQL, request bodies, mail, and stack traces even after automatic redaction.

Documentation

Guide Use it for
MCP server Installing webpprof-mcp and connecting AI coding agents
Integrations Framework, SQL, cache, queue, messaging, logging, and mail setup
Configuration Capture limits, filters, sampling, storage, import, and export
Dashboard Built-in and custom metrics, counters, and charts
Correlation and findings Context propagation, tags, middleware, and automatic analysis
Event reference Manual APIs, Meta, entity fields, and background work
SQL profiling Callsites, source links, EXPLAIN, and Go replay
Custom profilers Implementing an adapter for another dependency

Development

The repository uses go.work for local development; consumers do not need it. Each optional integration and the MCP command has its own go.mod.

make check

The check runs dependency isolation, module verification, go vet, all Go tests, JavaScript syntax validation, and whitespace checks.

License

webpprof is available under the MIT License.

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

Examples

Constants

View Source
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 Enabled

func Enabled() bool

Enabled reports whether a default profiler is active.

func IsSensitiveKey

func IsSensitiveKey(key string) bool

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

func LogCacheContext(ctx context.Context, cache Cache)

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

func LogCallableContext(ctx context.Context, callable Callable)

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

func LogEmailContext(ctx context.Context, email Email)

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

func LogEventContext(ctx context.Context, event Event)

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

func LogExceptionContext(ctx context.Context, exception Exception)

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

func LogHTTPCallContext(ctx context.Context, call HTTPCall)

LogHTTPCallContext records an outbound HTTP call with the default profiler and correlation inherited from ctx.

func LogJob

func LogJob(job Job)

LogJob records a background job with the default profiler.

func LogJobContext

func LogJobContext(ctx context.Context, job Job)

LogJobContext records a job with the default profiler and correlation inherited from ctx.

func LogLog

func LogLog(log Log)

LogLog records a structured log with the default profiler.

func LogLogContext

func LogLogContext(ctx context.Context, log Log)

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

func LogQueryContext(ctx context.Context, query Query)

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

func LogScheduleContext(ctx context.Context, schedule Schedule)

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

func LogTaskContext(ctx context.Context, task Task)

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

func ParentEntryIDFromContext(ctx context.Context) string

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

func RecordingEnabled(ctx context.Context) bool

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

func ShouldCaptureRequest(request *http.Request) bool

ShouldCaptureRequest applies the default profiler's exclusions, filters, sampling rate, and optional request limit.

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown gracefully stops the default profiler server and closes storage.

func TagsFromContext added in v0.2.0

func TagsFromContext(ctx context.Context) map[string]string

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

func WithParentEntry(ctx context.Context, entryID string) context.Context

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

func WithTags(ctx context.Context, tags map[string]string) context.Context

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

func WithoutCorrelation(ctx context.Context) context.Context

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.

func WithoutRecording

func WithoutRecording(ctx context.Context) context.Context

WithoutRecording returns a child context that suppresses context-aware profiler integrations downstream.

Types

type Address

type Address struct {
	Name  string `json:"name,omitempty"`
	Email string `json:"email"`
}

Address identifies one email sender or recipient.

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

type DashboardValueFunc func(context.Context) (float64, error)

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

type EventResult struct {
	Status  string
	Summary string
	Fields  map[string]any
	Err     error
}

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

func StartEvent(ctx context.Context, event Event) *EventSpan

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

func (s *EventSpan) Context() context.Context

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

func PanicException(recovered any) Exception

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

type Measurement struct {
	StartedAt time.Time
	Duration  time.Duration
	Err       error
}

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

func Measure(ctx context.Context, event Event, fn func(context.Context) error) Measurement

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

func MeasureTask(ctx context.Context, task Task, fn func(context.Context) error) Measurement

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

func WithAllowedOrigins(origins ...string) Option

WithAllowedOrigins permits the listed browser origins to access profiler endpoints. Blank origins are ignored.

func WithBasePath

func WithBasePath(path string) Option

WithBasePath changes the URL prefix used by the dashboard and JSON API. Empty paths and "/" leave the default /debug/webpprof prefix unchanged.

func WithBodyLimit

func WithBodyLimit(maxBytes int64) Option

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

func WithBrowserSession(session string) Option

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

func WithCallsiteKinds(kinds ...Kind) Option

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

func WithDashboardTimeout(timeout time.Duration) Option

WithDashboardTimeout limits how long one dashboard snapshot may spend collecting values from custom metric callbacks.

func WithDisabledKinds added in v0.2.0

func WithDisabledKinds(kinds ...Kind) Option

WithDisabledKinds prevents the listed entity kinds from being recorded.

func WithExcludedRequests

func WithExcludedRequests(patterns ...string) Option

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

func WithHTTPStatusAtLeast(status int) Option

WithHTTPStatusAtLeast retains requests whose final status is at least status.

func WithHTTPStatusCodes added in v0.2.0

func WithHTTPStatusCodes(codes ...int) Option

WithHTTPStatusCodes retains requests whose final status equals one of codes.

func WithMaxBytes

func WithMaxBytes(maxBytes int64) Option

WithMaxBytes bounds the approximate encoded size of entries kept in memory. Non-positive values leave the default limit unchanged.

func WithMaxEvents

func WithMaxEvents(maxEvents int) Option

WithMaxEvents bounds the number of entries kept in memory. Non-positive values leave the default limit unchanged.

func WithMinRequestDuration added in v0.2.0

func WithMinRequestDuration(duration time.Duration) Option

WithMinRequestDuration retains requests that took at least duration.

func WithNextRequests added in v0.2.0

func WithNextRequests(count int) Option

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

func WithQueryCallsite(enabled bool) Option

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

func WithQueueStatsTimeout(timeout time.Duration) Option

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

func WithRequestSampleRate(rate float64) Option

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

func WithRequestTags(tags map[string]string) Option

WithRequestTags retains requests containing every configured tag/value pair.

func WithRetention

func WithRetention(retention time.Duration) Option

WithRetention sets how long recorded entries remain available. Non-positive values leave the default retention unchanged.

func WithSecureCookie

func WithSecureCookie(isSecure bool) Option

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

func WithSidebarKinds(kinds ...Kind) Option

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

func WithStoragePath(storagePath string) Option

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

func WithStreamBuffer(size int) Option

WithStreamBuffer sets the per-subscriber live-event buffer size. Non-positive values leave the default size unchanged.

func WithToken

func WithToken(token string) Option

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

func New(router Router, options ...Option) *Profiler

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

func NewIf(enabled bool, router Router, options ...Option) *Profiler

NewIf calls New only when enabled. It is useful for environment-controlled setup and returns nil when disabled.

func Start

func Start(addr string, options ...Option) (*Profiler, error)

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

func (p *Profiler) BasePath() string

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

func (p *Profiler) BodyLimit() int64

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

func (p *Profiler) Close() error

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

func (p *Profiler) Enabled() bool

Enabled reports whether the receiver is non-nil.

func (*Profiler) LogCache

func (p *Profiler) LogCache(cache Cache)

LogCache records a cache operation and captures a callsite when configured.

func (*Profiler) LogCacheContext

func (p *Profiler) LogCacheContext(ctx context.Context, cache Cache)

LogCacheContext records a cache operation with this profiler and correlation inherited from ctx.

func (*Profiler) LogCallable added in v0.5.0

func (p *Profiler) LogCallable(callable Callable)

LogCallable records an explicitly invoked custom command and captures a callsite when configured.

func (*Profiler) LogCallableContext added in v0.5.0

func (p *Profiler) LogCallableContext(ctx context.Context, callable Callable)

LogCallableContext records an explicitly invoked command with this profiler. Request and parent correlation are removed because Callable is a root entity.

func (*Profiler) LogEmail

func (p *Profiler) LogEmail(email Email)

LogEmail records an outgoing email and captures a callsite when configured.

func (*Profiler) LogEmailContext

func (p *Profiler) LogEmailContext(ctx context.Context, email Email)

LogEmailContext records an email with this profiler and correlation inherited from ctx.

func (*Profiler) LogEvent

func (p *Profiler) LogEvent(event Event)

LogEvent records a custom application event.

func (*Profiler) LogEventContext

func (p *Profiler) LogEventContext(ctx context.Context, event Event)

LogEventContext records a custom event with this profiler and correlation inherited from ctx.

func (*Profiler) LogException

func (p *Profiler) LogException(exception Exception)

LogException records an application error or recovered panic.

func (*Profiler) LogExceptionContext

func (p *Profiler) LogExceptionContext(ctx context.Context, exception Exception)

LogExceptionContext records an exception with this profiler and correlation inherited from ctx.

func (*Profiler) LogHTTPCall

func (p *Profiler) LogHTTPCall(call HTTPCall)

LogHTTPCall records an outbound HTTP call and captures a callsite when configured.

func (*Profiler) LogHTTPCallContext

func (p *Profiler) LogHTTPCallContext(ctx context.Context, call HTTPCall)

LogHTTPCallContext records an outbound HTTP call with this profiler and correlation inherited from ctx.

func (*Profiler) LogJob

func (p *Profiler) LogJob(job Job)

LogJob records a background job and captures a callsite when configured.

func (*Profiler) LogJobContext

func (p *Profiler) LogJobContext(ctx context.Context, job Job)

LogJobContext records a job with this profiler and correlation inherited from ctx.

func (*Profiler) LogLog

func (p *Profiler) LogLog(log Log)

LogLog records a structured application log.

func (*Profiler) LogLogContext

func (p *Profiler) LogLogContext(ctx context.Context, log Log)

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

func (p *Profiler) LogQuery(query Query)

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

func (p *Profiler) LogQueryContext(ctx context.Context, query Query)

LogQueryContext records a query with this profiler and inherits tags, parent entry, and request correlation from ctx.

func (*Profiler) LogRequest

func (p *Profiler) LogRequest(request Request)

LogRequest records a completed request and stores its related entities as individually correlated entries. Retention filters may discard the request.

func (*Profiler) LogSchedule

func (p *Profiler) LogSchedule(schedule Schedule)

LogSchedule records a scheduled task and captures a callsite when configured.

func (*Profiler) LogScheduleContext

func (p *Profiler) LogScheduleContext(ctx context.Context, schedule Schedule)

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

func (p *Profiler) LogTask(task Task)

LogTask records a measured application task and captures a callsite when configured.

func (*Profiler) LogTaskContext added in v0.5.0

func (p *Profiler) LogTaskContext(ctx context.Context, task Task)

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

func (p *Profiler) ShouldCaptureRequest(request *http.Request) bool

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

func (p *Profiler) Shutdown(ctx context.Context) error

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

func (p *Profiler) StartEvent(ctx context.Context, event Event) *EventSpan

StartEvent starts a custom event using p. Pass span.Context() to nested work so its profiler entries use this event as their parent.

func (*Profiler) StartTask added in v0.5.0

func (p *Profiler) StartTask(ctx context.Context, task Task) *TaskSpan

StartTask starts a standalone Task using p. Pass span.Context() to nested work so profiler entries use the Task ID as ParentID.

func (*Profiler) URL

func (p *Profiler) URL() string

URL returns this profiler's dedicated-server dashboard URL, or an empty string when it does not own a server.

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

func StartQuery(ctx context.Context, query Query) *QuerySpan

StartQuery begins measuring query. Finish or FinishRows must be called to record it; a missing StartedAt timestamp is initialized automatically.

func (*QuerySpan) Finish

func (s *QuerySpan) Finish(err error)

Finish records the query without a rows-affected value. Repeated calls are ignored.

func (*QuerySpan) FinishRows

func (s *QuerySpan) FinishRows(rowsAffected int64, err error)

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

type RequestFilter func(*http.Request) bool

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

type RequestRetentionFilter func(Request) bool

RequestRetentionFilter decides whether a completed request and all of its related entities should be persisted.

type Router

type Router interface {
	Handle(string, http.Handler)
}

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

func (s Scope) Load(key any) (any, bool)

Load retrieves a value previously cached by this integration. Non-comparable keys are rejected and return no value.

func (Scope) LoadOrStore

func (s Scope) LoadOrStore(key, value any) (any, bool)

LoadOrStore returns an existing scoped value when present or stores value. The loaded result follows sync.Map semantics.

func (Scope) Profiler

func (s Scope) Profiler() *Profiler

Profiler returns the profiler associated with this integration call.

func (Scope) Store

func (s Scope) Store(key, value any)

Store caches value under a key scoped to this integration. It ignores non-comparable keys and inactive scopes.

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

type TaskResult struct {
	State  string
	Fields map[string]any
	Err    error
}

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 StartTask added in v0.5.0

func StartTask(ctx context.Context, task Task) *TaskSpan

StartTask starts a Task using the default profiler.

func (*TaskSpan) Context added in v0.5.0

func (s *TaskSpan) Context() context.Context

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.

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

Jump to

Keyboard shortcuts

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