slogx

package module
v0.0.0-...-810bc7e Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

slogx

Structured logging on log/slog for services: one line per event, fixed fields first, events defined once and routed to a log file, a security log, an event bus or a live viewer. Standard library only.

Callers only ever hold a *slog.Logger. Everything else is configuration.

time=2026-11-08T03:12:45.120Z level=WARN event=login_failed module=web src_ip=192.0.2.7 user=admin msg="login failed"
time=2026-11-08T03:12:46.002Z level=INFO module=db rows=3 msg=query

Quick start

package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/djylb/slogx"
)

var loginFailed = slogx.Def{
	Name:     "login_failed",
	Level:    slog.LevelWarn,
	Msg:      "login failed",
	Security: true,
	Limit:    "src_ip", // one line per source IP per minute
}

func main() {
	logs := slogx.New() // or slogx.Default with slogx.Module
	defer logs.Close()
	err := logs.Configure(slogx.Config{
		Level:        "info,db=debug",
		File:         slogx.Rotation{Path: "/var/log/app/app.log", MaxSize: 64 << 20, MaxFiles: 5},
		SecurityFile: slogx.Rotation{Path: "/var/log/app/security.log"},
		Memory:       2000,
	})
	if err != nil {
		slog.Error("log config", "err", err)
		os.Exit(1)
	}

	web := logs.Module("web")
	web.Info("listening", "addr", ":8080")
	slogx.Emit(context.Background(), web, &loginFailed, "src_ip", "192.0.2.7", "user", "admin")
}

The zero Config writes at info level to stderr: coloured on a terminal, logfmt otherwise. Configure replaces the whole pipeline atomically, so loggers already handed out keep working and a configuration reload needs no restart.

Concepts

  • Logs and modules: a Logs is a process's logging; logs.Module("db") returns a *slog.Logger whose lines carry module=db. Handler gives a handler without a module, for slog.SetDefault.
  • Def: an event definition: name, level, default message, whether it is a security event or a bus event, and how it is rate limited or sampled. slogx.Emit(ctx, logger, &def, args...) writes it; an argument keyed slogx.KeyMsg replaces the default message for one line. The record carries its definition, so libraries define their own events without a shared registry.
  • Route: a Match and one destination: an Output with an Encoder, a Memory, or a callback. Matches come ready-made (MatchLevels, MatchSecurity, MatchBus, MatchMinLevel) and combine with MatchAny and MatchAll. Config.Routes lists routes; Logs.Attach adds one for a consumer that comes and goes.
  • Levels: a default level and per-module ones (info,db=debug,net=warn). Levels().Override(module, level, ttl) makes a module more verbose for a while and Clear ends it early. Levels is an http.Handler to read and change them; mount it behind your own authorization.
  • Memory: the last entries as structured data, for a viewer: Query (level, module, event, time, text, incremental by sequence), Subscribe for new entries, Take to hand each entry out once.
  • Sampling: per event and key (Def.Limit), or first-N-then-every-M (Sampling) for plain lines; the next line that passes carries suppressed=<n>.
  • slogxtest: slogxtest.New records lines for assertions; slogxtest.ToTest(t) writes them to the test's own output.

Format

Every encoder writes the fixed fields first, in the order time, level, event, module, then the line's attributes, then msg, source and stack. The text (logfmt) and JSON forms carry the same keys. Values are quoted and escaped so no input can forge a line: an attribute named like a fixed field (time, level, event, module, msg, source, stack, suppressed) is written with a leading _, such as _source, control characters and bidi overrides are escaped, a value whose Error or String panics is written as !PANIC, and slogx.Redacted values as [REDACTED] (unless Config.LogSecrets, a development-only switch that warns when it turns on, writes them as they are). Pretty is for people and not meant to be parsed.

More

  • Outputs: files that rotate by size or age, with retention, compression and permissions, and reopen on request for an external logrotate (Logs.Reopen); Async queues lines and drops instead of blocking, reporting what it dropped as a log_dropped event.
  • Context: Config.ContextAppend appends attributes from a context.Context into the line's own buffer, such as request ids or the pprof labels a component runs under (PprofLabels, combined with JoinContext).
  • Diagnostics: Config.AddSource adds source=file:line; Config.StackFrom adds stacks from a level.
  • Capture: HTTPErrorLog for http.Server.ErrorLog turns TLS handshake errors into tls_handshake_failed events; StdLogger and CaptureStdLog take lines of the standard log package.
  • Cost: a disabled level costs one atomic load; an enabled line does not allocate.

The package examples show each of these in runnable form.

fail2ban

With a security file, a filter needs only the fixed fields:

failregex = ^time=\S* level=WARN event=login_failed module=\S+ src_ip=<HOST>(\s|$)

Pass the address as the event's first argument. An event line writes its own attributes right after module=, ahead of those of With, Config.ContextAppend and Config.Attrs, so the filter can anchor on it. Do not match .*src_ip=: a later field the client controls, such as a user name, could carry src_ip= of an innocent address. fail2ban strips the timestamp before matching, which leaves time= empty, hence \S*. An event with a Limit writes at most one line per key and minute, so each line stands for at least one failure in that minute: set maxretry and findtime in those terms (for example 3 lines in 10m).

License

Apache License 2.0

Documentation

Overview

Package slogx is structured logging on log/slog: one line per event, the fixed fields first in the order time, level, event, module, then the line's attributes, then msg. It adds to slog what an application needs around it: logfmt, JSON and terminal encoders; per-module levels with temporary overrides; event definitions shared by the log, a security log and an event bus; rate limiting and sampling; routes to files, rotating files, an in-memory viewer and callbacks; and capture of net/http and the standard library's log.

Callers only ever hold a *slog.Logger, from Logs.Module.

Example
package main

import (
	"bytes"
	"os"

	"github.com/djylb/slogx"
)

// stdout is a route that writes logfmt without the time to os.Stdout, so
// the examples' output is stable.
func stdout() slogx.Route {
	return slogx.Route{Output: slogx.WriterOutput(os.Stdout), Encoder: noTime{slogx.TextEncoder{}}}
}

func main() {
	logs := slogx.New()
	_ = logs.Configure(slogx.Config{
		Console: slogx.ConsoleOff,
		Level:   "info,db=debug",
		Routes:  []slogx.Route{stdout()},
	})
	defer logs.Close()

	logs.Module("web").Info("listening", "addr", ":8080")
	logs.Module("db").Debug("query", "rows", 3)
	logs.Module("cache").Debug("hidden")
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
level=INFO module=web addr=:8080 msg=listening
level=DEBUG module=db rows=3 msg=query

Index

Examples

Constants

View Source
const (
	// EventLogFallback is written at warn when a log file could not be
	// opened; its lines go to stderr.
	EventLogFallback = "log_fallback"
	// EventLogDropped is written at warn when an asynchronous output dropped
	// lines.
	EventLogDropped = "log_dropped"
	// EventTLSHandshakeFailed is written at debug, limited per src_ip, when
	// net/http reports a failed TLS handshake (HTTPErrorLog).
	EventTLSHandshakeFailed = "tls_handshake_failed"
	// EventLogSecrets is written at warn when Config.LogSecrets turns on:
	// Redacted values are written as they are from then on.
	EventLogSecrets = "log_secrets"
)

Names of the events slogx itself writes. Their definitions are fixed; Registered lists them.

View Source
const (
	KeyTime       = "time"
	KeyLevel      = "level"
	KeyEvent      = "event"
	KeyModule     = "module"
	KeyMsg        = "msg"
	KeySource     = "source"
	KeyStack      = "stack"
	KeySuppressed = "suppressed"
)

Keys of the fixed fields. An attribute with one of these keys is written as "_" + key, so no attribute can stand in for a fixed field.

View Source
const LevelOff = slog.Level(1 << 20)

LevelOff is above every level: nothing is written.

View Source
const LevelTrace = slog.Level(-8)

LevelTrace is below debug, for per-packet detail.

Variables

View Source
var Default = New()

Default is the Logs that Module uses.

View Source
var ErrTooManyOverrides = errors.New("slogx: too many level overrides")

ErrTooManyOverrides is returned by Override beyond Config.MaxOverrides modules.

Functions

func CaptureStdLog

func CaptureStdLog(l *slog.Logger, level slog.Level)

CaptureStdLog sends the standard library's default logger, which some libraries write to, to l at level: StdLogger for log's default logger.

func Emit

func Emit(ctx context.Context, l *slog.Logger, d *Def, args ...any)

Emit writes event d at its level to l with the given attributes (as slog's args), carrying the attributes of ctx (Config.ContextAppend). The line's message is d.Msg, or the value of the first argument with the key KeyMsg ("msg", as a key-value pair or a slog.Attr), which is then not written as an attribute. A security or bus event is passed on even when its level is filtered out of the main log.

Example
package main

import (
	"bytes"
	"context"
	"log/slog"
	"os"

	"github.com/djylb/slogx"
)

// stdout is a route that writes logfmt without the time to os.Stdout, so
// the examples' output is stable.
func stdout() slogx.Route {
	return slogx.Route{Output: slogx.WriterOutput(os.Stdout), Encoder: noTime{slogx.TextEncoder{}}}
}

func main() {
	loginFailed := slogx.Def{Name: "login_failed", Level: slog.LevelWarn, Msg: "login failed", Security: true}

	logs := slogx.New()
	_ = logs.Configure(slogx.Config{Console: slogx.ConsoleOff, Routes: []slogx.Route{stdout()}})
	defer logs.Close()

	ctx := context.Background()
	web := logs.Module("web")
	slogx.Emit(ctx, web, &loginFailed, "src_ip", "192.0.2.7", "user", "admin")
	slogx.Emit(ctx, web, &loginFailed, "src_ip", "192.0.2.8", slogx.KeyMsg, "account locked")
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
level=WARN event=login_failed module=web src_ip=192.0.2.7 user=admin msg="login failed"
level=WARN event=login_failed module=web src_ip=192.0.2.8 msg="account locked"

func HTTPErrorLog

func HTTPErrorLog(l *slog.Logger, listener string) *log.Logger

HTTPErrorLog returns a logger for http.Server.ErrorLog: TLS handshake failures become EventTLSHandshakeFailed events of listener, other lines are warnings.

Example
package main

import (
	"bytes"
	"os"

	"github.com/djylb/slogx"
)

// stdout is a route that writes logfmt without the time to os.Stdout, so
// the examples' output is stable.
func stdout() slogx.Route {
	return slogx.Route{Output: slogx.WriterOutput(os.Stdout), Encoder: noTime{slogx.TextEncoder{}}}
}

func main() {
	logs := slogx.New()
	_ = logs.Configure(slogx.Config{Console: slogx.ConsoleOff, Level: "debug", Routes: []slogx.Route{stdout()}})
	defer logs.Close()

	// As http.Server{ErrorLog: errLog} would write it:
	errLog := slogx.HTTPErrorLog(logs.Module("web"), "https")
	errLog.Print("http: TLS handshake error from 192.0.2.9:51234: EOF")
	errLog.Print("http: superfluous response.WriteHeader call")
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
level=DEBUG event=tls_handshake_failed module=web src_ip=192.0.2.9 src_port=51234 listener=https reason=eof
level=WARN module=web msg="http: superfluous response.WriteHeader call"

func JoinContext

func JoinContext(fns ...func(context.Context, []slog.Attr) []slog.Attr) func(context.Context, []slog.Attr) []slog.Attr

JoinContext combines context extractors for Config.ContextAppend; the attributes of each follow those of the one before. Nil extractors are skipped.

func LevelName

func LevelName(l slog.Level) string

LevelName returns the name a line carries for level. Levels between the named ones are written as the name below with an offset, as slog does: "INFO+2".

func MatchBus

func MatchBus(r *Record, _ *Levels) bool

MatchBus takes the events defined as bus events, whatever the levels.

func MatchLevels

func MatchLevels(r *Record, lv *Levels) bool

MatchLevels takes records at or above the level lv gives their module: the main log. It is the Match of a Route without one.

func MatchSecurity

func MatchSecurity(r *Record, _ *Levels) bool

MatchSecurity takes the events defined as security events, whatever the levels.

func Module

func Module(name string) *slog.Logger

Module returns a logger of Default whose lines carry module=name.

func ParseLevel

func ParseLevel(s string) (slog.Level, error)

ParseLevel reads one level name: trace, debug, info, warn, error, off, and the syslog-style names and numbers earlier configurations used.

func PprofLabels

func PprofLabels(ctx context.Context, dst []slog.Attr) []slog.Attr

PprofLabels appends the pprof labels ctx carries to dst as attributes, for Config.ContextAppend: a component labelled for profiles and tracebacks (such as with pprof.Do) then carries the same names in its log lines. Labels are not secret-safe; keep secrets out of them.

func Register

func Register(defs ...*Def)

Register lists defs for Registered, such as for generating documentation of the events an application writes. Logging does not need it. Two definitions of one name may differ in level (an urgent variant of an event) but not in where the event goes; registering such a pair panics.

func StdLogger

func StdLogger(l *slog.Logger, level slog.Level) *log.Logger

StdLogger returns a *log.Logger that writes each line to l at level.

Types

type AsyncOutput

type AsyncOutput struct {
	// OnDrop, when set before the first Write, is called from the queue's
	// goroutine once the queue has drained after dropping lines, with how
	// many were dropped since the last call. It may log: the queue has room.
	OnDrop func(dropped uint64)
	// contains filtered or unexported fields
}

AsyncOutput is the Output of Async.

func Async

func Async(o Output, size int) *AsyncOutput

Async returns an Output that hands lines to o on a goroutine of its own through a queue of size lines. A line that does not fit is dropped and counted rather than blocking the caller. Flush waits until the queue is empty; Close flushes and closes o. Both wait for o, so if o stalls, they stall too.

Example
package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"

	"github.com/djylb/slogx"
)

func main() {
	dir, _ := os.MkdirTemp("", "slogx-example")
	defer func() { _ = os.RemoveAll(dir) }()
	path := filepath.Join(dir, "app.log")

	// A file rotated at 64 MiB, the last 5 kept gzipped, written through a
	// queue of 1024 lines so a slow disk never slows the caller.
	f, err := slogx.OpenRotating(slogx.Rotation{Path: path, MaxSize: 64 << 20, MaxFiles: 5, Compress: true})
	if err != nil {
		fmt.Println(err)
		return
	}
	out := slogx.Async(f, 1024)
	logs := slogx.New()
	_ = logs.Configure(slogx.Config{
		Console: slogx.ConsoleOff,
		Routes:  []slogx.Route{{Output: out, Encoder: noTime{slogx.TextEncoder{}}}},
	})
	logs.Module("app").Info("started")
	logs.Close()
	_ = out.Close() // a route's Output is its owner's to close: this writes the queue and closes f

	b, _ := os.ReadFile(path)
	fmt.Print(string(b))
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
level=INFO module=app msg=started

func (*AsyncOutput) Close

func (a *AsyncOutput) Close() error

Close writes what is queued, then closes o; writes after it fail.

func (*AsyncOutput) Dropped

func (a *AsyncOutput) Dropped() uint64

Dropped reports how many lines did not fit in the queue.

func (*AsyncOutput) Flush

func (a *AsyncOutput) Flush() error

Flush waits until the lines queued before it are written and o flushed.

func (*AsyncOutput) Reopen

func (a *AsyncOutput) Reopen() error

Reopen reopens o when it is a Reopener.

func (*AsyncOutput) Write

func (a *AsyncOutput) Write(p []byte) error

Write queues a copy of p, in a buffer reused once the line is written, or drops it when the queue is full.

type Config

type Config struct {
	// Console is where the console goes; zero is stderr.
	Console Console
	// Format of the console and the files; zero is Auto.
	Format Format
	// Level is a default level and per-module ones, "info,db=debug".
	Level string
	// MaxOverrides bounds how many modules Levels.Override may override at
	// once; zero is 1024. Lowering it keeps the overrides already made.
	MaxOverrides int
	// File, when its Path is set, is a log file taking the same lines as
	// the console. A file that cannot be opened falls back to stderr, even
	// with ConsoleOff.
	File Rotation
	// SecurityFile, when set, receives every security event.
	SecurityFile Rotation
	// Memory, when positive, keeps that many entries for Logs.Memory. The
	// Memory survives a Configure with the same size, subscribers included.
	Memory int
	// Async, when positive, writes files through a queue of that many
	// lines, so a slow disk never slows the caller; lines that do not fit
	// are dropped, and a log_dropped event says how many.
	Async int
	// Routes are further destinations.
	Routes []Route

	// AddSource adds source=file:line to every line.
	AddSource bool
	// LogSecrets writes Redacted values as they are instead of
	// [REDACTED], for debugging during development only; never set it in
	// production. Turning it on writes an EventLogSecrets warning.
	// Logs.SetLogSecrets switches it without a Configure.
	LogSecrets bool
	// StackFrom, when not nil, adds the stack to lines at or above its
	// level, such as slog.LevelError. As with slog.HandlerOptions.Level, a
	// nil pointer inside the interface is not allowed.
	StackFrom slog.Leveler
	// Attrs are added to every line, events included, after all its other
	// attributes: such as instance= or host= to tell apart processes
	// writing to one place. A key of a fixed field gets a leading "_" like
	// any attribute's.
	Attrs []slog.Attr
	// ContextAppend appends to dst the attributes a context carries, such
	// as a request id, for lines logged with one, and returns the extended
	// slice, as append does. dst belongs to the line being written: append
	// to it, do not keep it. Appending into the line's own buffer lets an
	// extractor run without allocating.
	ContextAppend func(ctx context.Context, dst []slog.Attr) []slog.Attr
	// Sample, when set, samples plain lines (not events) per module,
	// level and message.
	Sample *Sampling
}

Config says where and how lines go. The zero Config writes at info level to stderr: coloured Pretty on a terminal, logfmt otherwise.

The fields up to Routes are shorthands for the common routes: a console, a file, a security file and an in-memory viewer, all but the security file taking the lines the level table lets through. Routes adds any others.

type Console

type Console int

Console is where Config writes its console lines.

const (
	// ConsoleStderr writes the console to os.Stderr.
	ConsoleStderr Console = iota
	// ConsoleStdout writes the console to os.Stdout.
	ConsoleStdout
	// ConsoleOff writes no console.
	ConsoleOff
)

type Def

type Def struct {
	Name  string
	Level slog.Level
	// Msg is the message of the event's lines; an Emit argument with the
	// key KeyMsg replaces it for that line.
	Msg string
	// Security events match MatchSecurity (a security log).
	Security bool
	// Bus events match MatchBus (an event bus, a webhook).
	Bus bool
	// Limit, when set, is the field whose value keys rate limiting: one
	// line per event and value per minute, the next carrying how many were
	// suppressed. "*" limits the event as a whole. Sample, when set, is
	// used instead.
	Limit  string
	Sample *Sampling
}

Def defines an event: its name, level and where else it goes. An application declares its events as package variables, so that the main log, the security log and an event bus all take an event from one definition. The record carries its Def, so two libraries may define events without knowing of each other.

func Registered

func Registered() []Def

Registered returns copies of the registered events, by name.

type Encoder

type Encoder interface {
	Encode(dst []byte, r *Record) []byte
}

Encoder turns a record into bytes appended to dst, one line ending in a newline. Every encoder writes the fixed fields first, in the order time, level, event, module, then the record's attributes, then msg, source and stack.

type Entry

type Entry struct {
	Seq  uint64    `json:"seq"`
	Time time.Time `json:"time"`
	// Level is the slog level, for ordering and filtering; LevelName the
	// name the line carries (LevelName).
	Level     slog.Level `json:"level_value"`
	LevelName string     `json:"level"`
	Module    string     `json:"module,omitempty"`
	Event     string     `json:"event,omitempty"`
	Msg       string     `json:"msg,omitempty"`
	Attrs     []Field    `json:"attrs,omitempty"`
}

Entry is a line kept by Memory, detached from the record it came from.

func (*Entry) Record

func (e *Entry) Record() Record

Record returns e as a record with string attributes, for an Encoder: enc.Encode(dst, &r).

type Field

type Field struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

Field is an attribute of an Entry, its value as text.

type Flusher

type Flusher interface {
	Flush() error
}

Flusher is an Output that holds lines back; Flush writes them out.

type Format

type Format int

Format names a built-in encoder.

const (
	// Auto is Pretty, coloured, on a console that is a terminal, and Text
	// everywhere else.
	Auto Format = iota
	// Text is logfmt: key=value pairs, values quoted when needed.
	Text
	// JSON is one JSON object per line.
	JSON
	// Pretty is for people: aligned, and coloured on a console that is a
	// terminal. It is not a format to parse.
	Pretty
)

func (Format) Encoder

func (f Format) Encoder() Encoder

Encoder returns the built-in encoder of f where no terminal is known, as for a file: Auto is TextEncoder and Pretty is PrettyEncoder without colour.

type JSONEncoder

type JSONEncoder struct{}

JSONEncoder writes one JSON object per line, with the keys of TextEncoder; numbers and booleans keep their type.

func (JSONEncoder) Encode

func (JSONEncoder) Encode(b []byte, r *Record) []byte

Encode implements Encoder.

type Levels

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

Levels is the level table of a Logs: a default and per-module levels, plus temporary overrides that expire. It is safe for concurrent use; reading a level costs one atomic load.

func (*Levels) Clear

func (l *Levels) Clear(module string)

Clear ends the override of module now; module returns to what Set gave.

func (*Levels) Of

func (l *Levels) Of(module string) slog.Level

Of returns the level of module now.

func (*Levels) Override

func (l *Levels) Override(module string, level slog.Level, ttl time.Duration) error

Override makes module ("" for the default and so every module) log down to level for ttl, after which it returns to what Set gave: a temporary debug or trace level while investigating. An override only ever makes a module more verbose, never quieter than Set made it, and replaces an earlier override of the same module. ttl must be positive; Clear ends an override early.

Example
package main

import (
	"bytes"
	"log/slog"
	"os"
	"time"

	"github.com/djylb/slogx"
)

// stdout is a route that writes logfmt without the time to os.Stdout, so
// the examples' output is stable.
func stdout() slogx.Route {
	return slogx.Route{Output: slogx.WriterOutput(os.Stdout), Encoder: noTime{slogx.TextEncoder{}}}
}

func main() {
	logs := slogx.New()
	_ = logs.Configure(slogx.Config{Console: slogx.ConsoleOff, Level: "info", Routes: []slogx.Route{stdout()}})
	defer logs.Close()

	db := logs.Module("db")
	db.Debug("before")
	_ = logs.Levels().Override("db", slog.LevelDebug, 10*time.Minute)
	db.Debug("during")
	logs.Levels().Clear("db")
	db.Debug("after")
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
level=DEBUG module=db msg=during

func (*Levels) ServeHTTP

func (l *Levels) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP shows the levels on GET, and on PUT or POST takes a JSON body {"level": "info,net=debug"} to Set, or {"module": "net", "level": "debug", "ttl": "10m"} to Override; {"module": "net", "ttl": "0"} clears the module's override, and any other ttl that is not positive is an error. The state it shows is {"level": ..., "overrides": {module: "debug until <RFC 3339 time>"}}. Mount it behind the application's own authorization.

func (*Levels) Set

func (l *Levels) Set(spec string) error

Set replaces the default and per-module levels as spec says, "info,db=debug,net=warn". Overrides stay until they expire.

func (*Levels) String

func (l *Levels) String() string

String returns the levels as Set reads them, without overrides.

type Logs

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

Logs is a process's logging. Its loggers keep working across Configure.

func New

func New() *Logs

New returns Logs that write logfmt at info level to stderr until Configure.

func (*Logs) Attach

func (l *Logs) Attach(r Route) (detach func(), err error)

Attach adds a route that stays across Configure until the returned function detaches it, for consumers that come and go: an event bus, a live viewer. It is checked like Config.Routes.

func (*Logs) Close

func (l *Logs) Close()

Close waits for the lines in flight, then closes the files and the Memory; lines after it go to stderr.

func (*Logs) Configure

func (l *Logs) Configure(c Config) error

Configure replaces where and how l writes; lines being written finish on the old outputs before those close. A file that cannot be opened falls back to stderr with a log_fallback line rather than failing; an invalid Console, Format, Level, route or sampling is an error and changes nothing.

func (*Logs) Flush

func (l *Logs) Flush()

Flush writes out what asynchronous outputs hold and syncs the files.

func (*Logs) Handler

func (l *Logs) Handler() slog.Handler

Handler returns a handler with no module, for slog.SetDefault or a library that takes one.

func (*Logs) Levels

func (l *Logs) Levels() *Levels

Levels returns the level table.

func (*Logs) Memory

func (l *Logs) Memory() *Memory

Memory returns the in-memory entries of Config.Memory. Without one it is nil, which keeps nothing: reads are empty, subscriptions closed.

func (*Logs) Module

func (l *Logs) Module(name string) *slog.Logger

Module returns a logger whose lines carry module=name.

func (*Logs) Reopen

func (l *Logs) Reopen()

Reopen reopens the log files, after an external rotation (SIGHUP).

func (*Logs) SetLogSecrets

func (l *Logs) SetLogSecrets(on bool)

SetLogSecrets switches Config.LogSecrets at once, for the lines written from then on; turning it on writes an EventLogSecrets warning. The next Configure sets it again from its Config.

type Match

type Match func(r *Record, lv *Levels) bool

Match decides whether a route takes a record. lv is the level table of the Logs the route belongs to, with its overrides applied, for a Match that compares a record with its module's level (as MatchLevels does); other matches may ignore it. A Match must not keep r or lv.

func MatchAll

func MatchAll(ms ...Match) Match

MatchAll takes what all of ms take.

func MatchAny

func MatchAny(ms ...Match) Match

MatchAny takes what any of ms takes.

func MatchMinLevel

func MatchMinLevel(level slog.Level) Match

MatchMinLevel takes records at or above level, whatever the module levels. Records below the level table reach it only on a Route with Below set.

type Memory

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

Memory keeps the last entries in memory for a viewer, such as a web page: Query reads them, Subscribe follows new ones, Take hands out each entry once. Use it as the destination of a Route (Route.Memory). A nil *Memory, such as Logs.Memory without Config.Memory, keeps nothing: its reads are empty and its subscriptions closed.

func NewMemory

func NewMemory(size int) *Memory

NewMemory keeps up to size entries.

func (*Memory) Query

func (m *Memory) Query(q Query) []Entry

Query returns the kept entries q selects, oldest first.

func (*Memory) Size

func (m *Memory) Size() int

Size is how many entries m keeps.

func (*Memory) Subscribe

func (m *Memory) Subscribe(ctx context.Context, q Query, size int) *Subscription

Subscribe follows the entries q selects (After, Since and Limit are ignored) through a queue of size entries. An entry that does not fit is dropped for this subscriber and counted, so a slow viewer never slows logging. The subscription ends when ctx is done, Close is called, or the Memory is retired by Configure or Logs.Close.

Example
package main

import (
	"context"
	"fmt"
	"log/slog"

	"github.com/djylb/slogx"
)

func main() {
	logs := slogx.New()
	_ = logs.Configure(slogx.Config{Console: slogx.ConsoleOff, Memory: 100})
	defer logs.Close()

	sub := logs.Memory().Subscribe(context.Background(), slogx.Query{MinLevel: slog.LevelWarn}, 16)
	defer sub.Close()
	logs.Module("web").Info("ignored")
	logs.Module("web").Warn("slow request", "ms", 900)
	e := <-sub.C()
	fmt.Println(e.LevelName, e.Module, e.Msg, e.Attrs[0].Key, e.Attrs[0].Value)
}
Output:
WARN web slow request ms 900

func (*Memory) Take

func (m *Memory) Take() []Entry

Take returns the kept entries no earlier Take returned, oldest first.

func (*Memory) Text

func (m *Memory) Text(q Query, enc Encoder) string

Text returns the kept entries q selects encoded with enc, for a plain download or an application that polls for lines. Pass Query{After: seq} to read only what came after the entry seq; to hand each entry out once, encode the entries of Take (Entry.Record).

type Output

type Output interface {
	Write(line []byte) error
	Close() error
}

Output receives encoded lines, one per Write. Write must be safe for concurrent use, and must not keep line after it returns: the buffer is reused.

func WriterOutput

func WriterOutput(w io.Writer) Output

WriterOutput writes lines to w under a lock; Close closes w only if it is an io.Closer other than os.Stdout or os.Stderr.

type PrettyEncoder

type PrettyEncoder struct {
	Color bool
}

PrettyEncoder writes "15:04:05.000 WARN module event msg key=value".

func (PrettyEncoder) Encode

func (e PrettyEncoder) Encode(b []byte, r *Record) []byte

Encode implements Encoder.

type Query

type Query struct {
	After    uint64       // entries with a larger Seq
	Since    time.Time    // at or after
	MinLevel slog.Leveler // at or above, when not nil (nor a nil pointer)
	Modules  []string
	Events   []string
	Text     string // contained in msg or a value, case-insensitive
	Limit    int    // newest Limit entries; zero for all
}

Query selects entries. The zero Query selects everything.

type Record

type Record struct {
	Time   time.Time
	Level  slog.Level
	Module string
	// Event is the event name; Def its definition when the line was
	// written with Emit.
	Event string
	Def   *Def
	Attrs []slog.Attr
	Msg   string
	// Source is "file:line" of the call when Config.AddSource is set.
	Source string
	// Stack is the goroutine stack when the line is at or above
	// Config.StackFrom.
	Stack string
	// contains filtered or unexported fields
}

Record is a line on its way to the routes: attributes resolved, groups flattened into dotted keys, event and module taken out into their fixed places. Encoders and outputs may read it; they must not keep it after returning, as it is reused.

func (*Record) Attr

func (r *Record) Attr(key string) (slog.Value, bool)

Attr returns the value of the attribute key and whether it is present.

func (*Record) Clone

func (r *Record) Clone() Record

Clone returns a copy of r that may be kept.

type Redacted

type Redacted string

Redacted is a secret value: it is written as [REDACTED], or as it is while Config.LogSecrets is on. Wrap secrets in it when they must travel with other values. A Redacted message (the msg argument of Emit) is always [REDACTED].

func (Redacted) LogValue

func (Redacted) LogValue() slog.Value

LogValue implements slog.LogValuer.

type Reopener

type Reopener interface {
	Reopen() error
}

Reopener is an Output backed by a file that an external rotation may move away; Reopen opens it again.

type Rotating

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

Rotating is an Output to a file that rotates itself: the full file is renamed to <name>-<UTC time><ext> and a new one started. Compression and pruning of rotated files run in order on one goroutine of its own, so they never race each other or the writer.

func OpenRotating

func OpenRotating(c Rotation) (*Rotating, error)

OpenRotating opens the file of c, creating its directory.

func (*Rotating) Close

func (r *Rotating) Close() error

Close closes the file and waits for compression and pruning; writes after it fail.

func (*Rotating) Flush

func (r *Rotating) Flush() error

Flush writes out the buffer and syncs the file to disk.

func (*Rotating) Reopen

func (r *Rotating) Reopen() error

Reopen closes and reopens the file, after an external rotation.

func (*Rotating) Write

func (r *Rotating) Write(p []byte) error

Write appends p to the file, or to the buffer with BufferSize, rotating the file first when p would take it past MaxSize or the file is older than Every. With a buffer, the error of writing earlier lines out, including by the FlushInterval timer, is returned by the next Write, Flush or Close.

type Rotation

type Rotation struct {
	Path string
	// MaxSize is the size in bytes at which the file rotates.
	MaxSize int64
	// Every is the age at which the file rotates.
	Every time.Duration
	// MaxFiles is how many rotated files are kept, newest first.
	MaxFiles int
	// MaxAge is how long rotated files are kept, by the time in their name.
	MaxAge time.Duration
	// BufferSize, when positive, collects lines in a buffer of that many
	// bytes and writes them to the file together, instead of one write
	// per line. The buffer is written out when the next line does not fit,
	// FlushInterval after its first line, on Flush, Reopen, rotation and
	// Close. Lines still in the buffer are lost if the process dies
	// without Close. Zero or negative writes every line at once.
	BufferSize int
	// FlushInterval bounds how long a buffered line waits for the file;
	// zero is one second, negative never flushes on time (only on size,
	// Flush, Reopen, rotation and Close). Unused without BufferSize.
	FlushInterval time.Duration
	// Compress gzips rotated files.
	Compress bool
	// Mode is the permission of new log files; zero is 0640, readable by
	// the owner's group (such as an admin group running fail2ban) and no
	// one else. Directories made for them get the same bits plus search.
	Mode os.FileMode
}

Rotation is a log file and when to rotate it. Zero MaxSize means 64 MiB; negative means never rotate by size. Every, when positive, also rotates a file that has been written for that long. Zero MaxFiles and MaxAge keep every rotated file.

type Route

type Route struct {
	Name  string
	Match Match // nil is MatchLevels
	// Below makes the route see records below the level table, for a Match
	// that asks for more than the main log does. Lines are then built even
	// when no other route wants them, which costs.
	Below bool

	Encoder Encoder // nil is TextEncoder
	Output  Output
	Memory  *Memory
	// Func receives the record; it must not keep the record or its Attrs,
	// and must not block. Clone what it needs (Record.Clone).
	Func func(*Record)
}

Route sends the records Match takes to one destination: encoded to Output, kept in Memory, or handed to Func. Exactly one of them is set. Logs never closes a route's Output; its owner does, after the route is gone (Configure without it, Logs.Close, or detach).

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log/slog"
	"os"

	"github.com/djylb/slogx"
)

// stdout is a route that writes logfmt without the time to os.Stdout, so
// the examples' output is stable.
func stdout() slogx.Route {
	return slogx.Route{Output: slogx.WriterOutput(os.Stdout), Encoder: noTime{slogx.TextEncoder{}}}
}

func main() {
	keyRevoked := slogx.Def{Name: "key_revoked", Level: slog.LevelInfo, Bus: true}

	logs := slogx.New()
	// The main log takes warnings and above; a bus route takes the bus
	// events whatever their level.
	_ = logs.Configure(slogx.Config{
		Console: slogx.ConsoleOff,
		Level:   "warn",
		Routes: []slogx.Route{stdout(), {Name: "bus", Match: slogx.MatchBus, Func: func(r *slogx.Record) {
			fmt.Println("bus:", r.Event)
		}}},
	})
	defer logs.Close()

	slogx.Emit(context.Background(), logs.Module("auth"), &keyRevoked, "key", "k1")
	logs.Module("auth").Warn("clock skew")
}

// noTime drops the time field so the example output is stable.
type noTime struct{ slogx.Encoder }

func (e noTime) Encode(b []byte, r *slogx.Record) []byte {
	line := e.Encoder.Encode(nil, r)
	if _, rest, ok := bytes.Cut(line, []byte(" ")); ok {
		return append(b, rest...)
	}
	return append(b, line...)
}
Output:
bus: key_revoked
level=WARN module=auth msg="clock skew"

type Sampling

type Sampling struct {
	First      int
	Thereafter int
	Tick       time.Duration
}

Sampling keeps a burst of lines and then a fraction: per key and Tick, the first First lines pass, then every Thereafter-th (zero: none). The next line that passes carries suppressed=<count>. Zero Tick is one minute. Def.Limit is the special case First 1, Thereafter 0.

A sampler tracks about 8192 keys, split evenly over its shards (one, until contention makes it split). Beyond a shard's share, lines of new keys in that shard share its overflow key, so a flood of distinct keys (such as source addresses an attacker picks) is limited as one key per shard.

type Subscription

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

Subscription follows new entries.

func (*Subscription) C

func (s *Subscription) C() <-chan Entry

C delivers entries; it closes when the subscription ends.

func (*Subscription) Close

func (s *Subscription) Close()

Close ends the subscription.

func (*Subscription) Dropped

func (s *Subscription) Dropped() uint64

Dropped reports how many entries did not fit in the queue.

type TextEncoder

type TextEncoder struct{}

TextEncoder writes logfmt.

func (TextEncoder) Encode

func (TextEncoder) Encode(b []byte, r *Record) []byte

Encode implements Encoder.

Directories

Path Synopsis
internal
leakcheck
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
Package slogxtest records slogx lines for tests to assert on.
Package slogxtest records slogx lines for tests to assert on.

Jump to

Keyboard shortcuts

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