sloghook

package
v0.0.0-...-81c9f84 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0

Documentation

Overview

Package sloghook provides a bun query hook that logs queries using slog and emits Prometheus histograms for query latency.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithCallsite

func WithCallsite(ctx context.Context, callsite string) context.Context

WithCallsite returns a context carrying a bounded callsite label for db_query_duration_seconds. Callers must pass a value drawn from a small, known set (e.g. "uptimebar.bucket_availability", "results.list") — never anything derived from the raw SQL string or from request input, or the metric's cardinality stops being bounded.

Types

type QueryHook

type QueryHook struct {
	// Verbose includes the full query in logs (may contain sensitive data).
	// Affects logging only; metrics are always emitted.
	Verbose bool

	// Backend is the label value used on Prometheus metrics
	// ("sqlite" or "postgres").
	Backend string

	// SlowThreshold logs a successful query at WARN when it takes at least
	// this long. Zero (the default zero value) disables slow-query logging
	// entirely — failures still log at WARN and everything else at DEBUG.
	SlowThreshold time.Duration

	// ThrottleInterval bounds how often the same normalized statement may
	// log a slow-query WARN. Zero (the default zero value) falls back to
	// defaultSlowQueryThrottleInterval; only tests override this.
	ThrottleInterval time.Duration

	// Now overrides the clock used for throttling (tests). Nil uses time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

QueryHook is a bun query hook that logs SQL queries via slog and observes query latency via Prometheus.

func New

func New(verbose bool, backend string, slowThreshold time.Duration) *QueryHook

New creates a new bun query hook. verbose controls whether full statements are written to slog; backend ("sqlite" or "postgres") is attached as a label to the emitted Prometheus metrics. slowThreshold logs a successful query at WARN once it takes at least that long; 0 disables slow-query logging.

func (*QueryHook) AfterQuery

func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent)

AfterQuery is called after executing a query. Emits the query-latency histogram, increments busy-retry counter on contention errors, and writes a slog line at DEBUG (success, below threshold), WARN (slow success), or WARN (failure) level.

func (*QueryHook) BeforeQuery

func (h *QueryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context

BeforeQuery is called before executing a query.

Jump to

Keyboard shortcuts

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