logring

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package logring keeps the most recent log records in a bounded in-memory ring so a process can search its own logs without leaving the process.

It is an slog.Handler, so it composes with this module's fan-out:

slogconf.AddHandler(logring.New(logring.Options{}))

The ring is a debugging aid, not a log store. It is bounded, it is per process, and it dies with the process — the moment you most want logs (a crash) is the moment it is gone. Ship logs somewhere durable as well.

Index

Constants

View Source
const (
	// DefaultMaxBytes bounds the ring by the size of the records it holds
	// rather than a record count: one pathological 100 KB line must not be
	// able to evict a hundred useful ones.
	DefaultMaxBytes = 100 << 20 // 100 MiB

	// DefaultMaxRecordBytes drops any single record larger than this instead
	// of letting it evict a large share of the ring on its own.
	DefaultMaxRecordBytes = 1 << 20 // 1 MiB

	// DefaultLevel skips DEBUG by default. A service logging every SQL
	// statement at DEBUG fills any ring with query traces in seconds and
	// buries the records worth searching for.
	DefaultLevel = slog.LevelInfo

	// DefaultSearchLimit bounds an unbounded Search so a caller cannot
	// accidentally pull the whole ring into a response.
	DefaultSearchLimit = 200
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Attr

type Attr struct {
	Key   string
	Value string
}

Attr is one captured attribute, rendered to its string form at capture time.

The value is a string rather than a slog.Value because a stored Value can retain arbitrary caller objects, and a ring holding the last 100 MiB of records would pin every one of them for as long as the record survives. Capture time is also the only moment a LogValuer still resolves to what was actually logged.

type Entry

type Entry struct {
	Time  time.Time
	Level slog.Level
	Msg   string
	Line  string
	Attrs []Attr
}

Entry is one captured record: the formatted line exactly as the configured handler wrote it, minus its trailing newline, plus the fields needed to filter without re-parsing it.

Attrs carries the record's attributes INCLUDING those bound earlier through slog.Logger.With, flattened to dotted keys. It is captured from the slog.Record rather than parsed back out of Line, which is what makes attribute search work identically whether the ring stores JSON or text.

func (Entry) Attr

func (e Entry) Attr(key string) (string, bool)

Attr returns the value bound to key, and whether it was present at all.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler captures records into a bounded ring. Safe for concurrent use.

func New

func New(opts Options) *Handler

New builds a ring handler. Add it to a fan-out rather than installing it as the only handler — on its own it captures logs and emits nothing.

func (*Handler) Clear

func (h *Handler) Clear()

Clear discards every retained entry. The dropped counter is a lifetime total and survives, so Stats keeps reporting records the ring refused as oversized.

func (*Handler) Count

func (h *Handler) Count(opts SearchOptions) int

Count reports how many entries match, without materialising them. Limit and Offset are ignored — the point is the total a paged Search would walk.

func (*Handler) Enabled

func (h *Handler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the ring retains records at this level.

func (*Handler) Handle

func (h *Handler) Handle(ctx context.Context, r slog.Record) error

Handle formats the record and appends it, evicting oldest-first to stay under the byte cap.

func (*Handler) Len

func (h *Handler) Len() int

Len reports how many records the ring currently holds.

The ring is bounded by BYTES, not by record count, so this moves with the size of what was logged rather than tracking any fixed capacity — see Size.

func (*Handler) Search

func (h *Handler) Search(opts SearchOptions) Page

Search returns one page of matches, newest first unless opts.Ascending, together with the total that page was drawn from.

Total is what makes paging deliberate rather than guesswork: without it a full page and the last page are indistinguishable, so a reader cannot tell whether they have seen everything. It is counted in the SAME locked walk that collects the page, so the two always describe the same ring — computing them from two separate reads would let records arrive or evict in between, and paging on top of that can skip or repeat records.

The cost of that guarantee is a full walk: the total is unknowable without visiting every entry, so this cannot stop early once the page is full.

func (*Handler) Size

func (h *Handler) Size() int

Size reports how many bytes the retained records currently occupy.

This is the number the ring bounds itself by, so it is what to compare against Options.MaxBytes — and what to watch if you want to know how close the ring is to evicting. It counts everything an entry retains: the formatted line, the message, and the captured attributes.

Stats returns the same number alongside the entry and drop counts. This exists because reading one value out of a three-value return reads badly:

_, bytes, _ := ring.Stats()   // vs
bytes := ring.Size()

func (*Handler) Stats

func (h *Handler) Stats() (int, int, uint64)

Stats reports, in order, how many entries the ring holds, how many bytes they occupy, and how many records it has dropped for being oversized.

Use it when you want all three consistently — they are read under one lock, so they always describe the same moment. For a single value, Len and Size read better.

func (*Handler) Tail

func (h *Handler) Tail(n int) []Entry

Tail returns the newest n entries in chronological order, unfiltered. It is the "show me what just happened" read, where Search is the "find me that one record" read.

func (*Handler) WithAttrs

func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a handler writing to the SAME ring with the attrs applied.

func (*Handler) WithGroup

func (h *Handler) WithGroup(name string) slog.Handler

WithGroup returns a handler writing to the SAME ring with the group applied.

type Options

type Options struct {
	// MaxBytes caps the total size of retained records. <= 0 uses
	// DefaultMaxBytes.
	MaxBytes int

	// MaxRecordBytes drops any single record larger than this. <= 0 uses
	// DefaultMaxRecordBytes. It is clamped to MaxBytes — see New.
	MaxRecordBytes int

	// Level is the minimum level retained. nil uses DefaultLevel (INFO).
	Level slog.Leveler

	// Text stores human-readable lines instead of JSON. Default is JSON, so
	// the retained line matches what a JSON-configured process ships.
	//
	// This chooses the format of Line and nothing else. Attribute search reads
	// Entry.Attrs, captured from the record itself, so it behaves identically
	// either way.
	Text bool
}

Options configures a ring. The zero value is usable — every field falls back to its Default* constant.

type Page

type Page struct {
	// Entries is the page itself, ordered as the search asked for.
	Entries []Entry

	// Total is how many entries matched the filters BEFORE Limit and Offset
	// were applied. It is counted in the same locked walk that collected
	// Entries, so the two always describe the same ring.
	Total int

	// Offset is echoed back, so a caller paging through a result does not have
	// to carry it alongside the response.
	Offset int
}

Page is one bounded read plus the total it was drawn from.

type SearchOptions

type SearchOptions struct {
	// Contains keeps only entries whose line contains this substring
	// (case-insensitive).
	Contains string

	// Exclude drops any entry whose line contains this substring
	// (case-insensitive). Applied alongside Contains, so the two compose into
	// "this but not that".
	Exclude string

	// Match keeps only entries whose line matches this expression.
	//
	// It is a compiled *regexp.Regexp rather than a pattern string so a bad
	// pattern is a caller-side error at compile time, instead of forcing
	// Search to grow an error return or to swallow it silently.
	Match *regexp.Regexp

	// Attrs keeps only entries carrying every one of these key/value pairs
	// exactly. Keys are dotted for grouped attrs — a logger with
	// WithGroup("http") logging "status" matches under "http.status".
	//
	// This reads the captured attributes, NOT the formatted line, so it works
	// the same whether the ring stores JSON or text.
	Attrs map[string]string

	// MinLevel keeps only records at or above this level. nil applies no
	// level filter at all.
	//
	// It is a Leveler rather than a slog.Level on purpose: slog.Level(0) is
	// LevelInfo, so a plain slog.Level field would make the zero value of
	// SearchOptions silently hide every DEBUG record the ring retained.
	MinLevel slog.Leveler

	// Levels keeps only records at exactly these levels, for the "warnings and
	// errors but not info" read a floor cannot express. Empty applies no
	// filter. Combined with MinLevel, both have to pass.
	Levels []slog.Level

	// Since keeps only records at or after this instant.
	Since time.Time

	// Until keeps only records at or before this instant.
	Until time.Time

	// Limit caps the results. <= 0 uses DefaultSearchLimit.
	Limit int

	// Offset skips this many matches before collecting, for paging through a
	// result larger than Limit. Skipping happens after filtering, in the same
	// order the results come back.
	Offset int

	// Ascending returns oldest first instead of newest first.
	Ascending bool
}

SearchOptions filters a ring read. The zero value returns everything, newest first, capped at DefaultSearchLimit.

Jump to

Keyboard shortcuts

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