serverlog

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package serverlog mirrors backend slog Error+Warn records into a MariaDB table so admins can debug from the UI without shelling into the host for `journalctl`.

Counterpart of `clienterror` (frontend errors). Same opinionated retention strategy: row cap + age cap, both configurable via env.

Architecture:

slog.Logger
 ├─► base handler (TextHandler → stdout/journalctl, unchanged)
 └─► serverlog.Handler
      └─► non-blocking channel send → batcher goroutine
           └─► bulk INSERT into server_errors every 1s or 100 events

The handler is non-blocking: a full channel drops the event and emits a single rate-limited journalctl warning. Slow DB writes MUST NOT slow down the request path.

Read path: GET /api/admin/server-errors with filters (since/until/level/path/dev/request_id/limit), drilldown via GET /api/admin/server-errors/{id} for the full attrs JSON + stack trace.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("server error not found")

Functions

func AttachDevUser

func AttachDevUser(ctx context.Context, devUserID int64) context.Context

AttachDevUser stamps the authenticated dev's id under this ctx so subsequent slog calls are attributed to them.

func AttachHTTP

func AttachHTTP(ctx context.Context, r *http.Request, requestID string) context.Context

AttachHTTP returns a copy of ctx with the request's identifying fields stamped, so slog calls under this ctx can be attributed.

Types

type Filter

type Filter struct {
	Level     string    // "ERROR" | "WARN" — empty = any
	Path      string    // substring match on http_path
	DevUserID int64     // 0 = any
	RequestID string    // exact match
	Resolved  *bool     // nil = any, false = unresolved only, true = resolved only
	Since     time.Time // zero = no lower bound
	Until     time.Time // zero = no upper bound
	Limit     int       // <=0 = default 100, capped at 500
}

Filter — list query parameters. All fields zero-value-safe.

type Handler

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

Handler — slog.Handler that mirrors records into the `server_errors` table via a buffered channel + batcher goroutine.

Wraps a base handler (the one that already writes to journalctl) so callers don't need to log twice. Use serverlog.NewLogger to build a slog.Logger that fans out to both base + recorder.

func New

func New(ctx context.Context, base slog.Handler, repo *Repo, cfg HandlerConfig) *Handler

New constructs the handler + starts the batcher goroutine. Cancel `ctx` (process shutdown) to drain in-flight records and stop the goroutine. The repo's *bun.DB is shared with the rest of the app — no separate connection pool.

func (*Handler) Enabled

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

Enabled — slog.Handler interface. Always defer to the base for stdout output; we additionally evaluate cfg.MinLevel for DB mirroring inside Handle.

func (*Handler) Handle

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

Handle — fan out to base + maybe enqueue for DB.

func (*Handler) WithAttrs

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

WithAttrs / WithGroup — slog.Handler interface. Wrap the base.

func (*Handler) WithGroup

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

type HandlerConfig

type HandlerConfig struct {
	// MinLevel — only records at this level or above mirror to DB.
	// Defaults to slog.LevelWarn so warnings + errors are captured.
	MinLevel slog.Level

	// BufferSize — channel capacity. Records are dropped when full
	// (with a single rate-limited journalctl warning). Default 1024.
	BufferSize int

	// FlushInterval — max time a record waits in the batch before
	// the batcher kicks. Default 1s.
	FlushInterval time.Duration

	// MaxBatchSize — max records in one INSERT. Default 100.
	MaxBatchSize int
}

HandlerConfig — operator knobs. Defaults are sensible for a single-host deploy; raise on a busy multi-tenant box.

type Repo

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

func NewRepo

func NewRepo(db *bun.DB) *Repo

func (*Repo) EnforceRowCap

func (r *Repo) EnforceRowCap(ctx context.Context, maxRows int64) (int64, error)

EnforceRowCap deletes the oldest rows until the table is at or below maxRows. No-op when below the cap. Idempotent.

func (*Repo) Get

func (r *Repo) Get(ctx context.Context, id int64) (*ServerError, error)

Get loads a single event with all attrs / stack trace populated.

func (*Repo) InsertBatch

func (r *Repo) InsertBatch(ctx context.Context, rows []ServerErrorRow) error

InsertBatch bulk-inserts a batch of records. Used by the slog handler's batcher goroutine; failures are logged but not surfaced (we can't loop a logging error back into the same logger).

func (*Repo) List

func (r *Repo) List(ctx context.Context, f Filter) ([]ServerError, error)

List returns events newest-first, joined to users for the username column the UI shows. Filters compose with AND.

func (*Repo) PruneOlderThan

func (r *Repo) PruneOlderThan(ctx context.Context, cutoff time.Time, resolvedOnly bool) (int64, error)

PruneOlderThan deletes any row created before `cutoff`. Returns rows deleted. Resolved rows get a tighter cutoff (callers compute it themselves and call this once for each bucket).

func (*Repo) Reopen

func (r *Repo) Reopen(ctx context.Context, id int64) error

Reopen clears the resolved markers.

func (*Repo) Resolve

func (r *Repo) Resolve(ctx context.Context, id, byDevID int64) error

Resolve marks an event as triaged.

type ServerError

type ServerError struct {
	ID                  int64      `json:"id"`
	Level               string     `json:"level"`
	Message             string     `json:"message"`
	Source              string     `json:"source,omitempty"`
	RequestID           string     `json:"request_id,omitempty"`
	HTTPMethod          string     `json:"http_method,omitempty"`
	HTTPPath            string     `json:"http_path,omitempty"`
	HTTPStatus          int        `json:"http_status,omitempty"`
	DevUserID           int64      `json:"dev_user_id,omitempty"`
	DevUsername         string     `json:"dev_username,omitempty"`
	AttrsJSON           string     `json:"attrs_json,omitempty"`
	StackTrace          string     `json:"stack_trace,omitempty"`
	ResolvedAt          *time.Time `json:"resolved_at,omitempty"`
	ResolvedByDevUserID int64      `json:"resolved_by_dev_user_id,omitempty"`
	CreatedAt           time.Time  `json:"created_at"`
}

ServerError is the API/service shape — same fields as the generated Bun struct but with non-pointer simple types for JSON ergonomics.

type ServerErrorRow

type ServerErrorRow struct {
	bun.BaseModel `bun:"table:server_errors,alias:se"`

	ID                  int64      `bun:"id,pk,autoincrement" json:"id" db:"id"`
	Level               string     `bun:"level,notnull" json:"level" db:"level"`
	Message             string     `bun:"message,notnull" json:"message" db:"message"`
	Source              *string    `bun:"source" json:"source,omitempty" db:"source"`
	RequestID           *string    `bun:"request_id" json:"request_id,omitempty" db:"request_id"`
	HttpMethod          *string    `bun:"http_method" json:"http_method,omitempty" db:"http_method"`
	HttpPath            *string    `bun:"http_path" json:"http_path,omitempty" db:"http_path"`
	HttpStatus          *int       `bun:"http_status" json:"http_status,omitempty" db:"http_status"`
	DevUserID           *int64     `bun:"dev_user_id" json:"dev_user_id,omitempty" db:"dev_user_id"`
	AttrsJSON           *string    `bun:"attrs_json" json:"attrs_json,omitempty" db:"attrs_json"`
	StackTrace          *string    `bun:"stack_trace" json:"stack_trace,omitempty" db:"stack_trace"`
	ResolvedAt          *time.Time `bun:"resolved_at" json:"resolved_at,omitempty" db:"resolved_at"`
	ResolvedByDevUserID *int64     `bun:"resolved_by_dev_user_id" json:"resolved_by_dev_user_id,omitempty" db:"resolved_by_dev_user_id"`
	CreatedAt           time.Time  `bun:"created_at,notnull,nullzero,default:current_timestamp" json:"created_at" db:"created_at"`
}

ServerErrorRow is the Bun row shape for the shared server_errors table. It intentionally lives in the SDK so logging does not depend on an application service's generated domain package.

type Service

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

Service wraps the Repo with admin-facing operations and the retention pruner goroutine.

func NewService

func NewService(repo *Repo, cfg ServiceConfig, logger *slog.Logger) *Service

func (*Service) Get

func (s *Service) Get(ctx context.Context, id int64) (*ServerError, error)

Get → drilldown handler.

func (*Service) List

func (s *Service) List(ctx context.Context, f Filter) ([]ServerError, error)

List → admin handler.

func (*Service) Reopen

func (s *Service) Reopen(ctx context.Context, id int64) error

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, id, byDevID int64) error

Resolve / Reopen → admin actions.

func (*Service) StartPruner

func (s *Service) StartPruner(ctx context.Context)

StartPruner kicks off the retention goroutine. Cancel ctx (process shutdown) to stop it. Idempotent — caller should call once at boot.

type ServiceConfig

type ServiceConfig struct {
	UnresolvedRetainFor time.Duration // unresolved rows older than this drop
	ResolvedRetainFor   time.Duration // resolved rows older than this drop
	MaxRows             int64         // hard ceiling — oldest rows pruned past this
	PruneInterval       time.Duration // how often the pruner ticks
}

ServiceConfig — operator knobs for retention. Defaults are 30d (unresolved) / 7d (resolved) and 10k row cap. Pass values through from cfg to keep the deployment-portability rule (no literals in code that change between hosts).

Jump to

Keyboard shortcuts

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