logging

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 22 Imported by: 1 module, 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.

Documentation

Overview

Package logging writes the JSON line of contract.md section 2 through log/slog: output selection by environment, level, dated files with retention and a size cap, the 64 KiB line limit, text rendering on stderr, and per-work attributes read from the context.

id := identity.New("myapp")
log := logging.New(id, logging.KeepDays(14), logging.MaxFileBytes(100<<20))
log.InfoContext(ctx, "listening", "addr", ":8080")
log.LogAttrs(ctx, slog.LevelInfo, "", logging.Event("job.progress"), slog.String("job.name", "reindex"))

Index

Constants

View Source
const (
	OutputStdout = "stdout"
	OutputFile   = "file"
	OutputStderr = "stderr"
)

The outputs of contract.md section 5. Stderr renders text; the other two write JSON lines.

View Source
const LevelFatal = slog.LevelError + 4

LevelFatal is the level written as FATAL (severity_number 21).

View Source
const MaxKeyBytes = 128

MaxKeyBytes is the longest key written; longer keys are dropped (contract.md section 2.3).

View Source
const MaxLineBytes = 64 << 10

MaxLineBytes is the longest line written, newline included (contract.md section 2.3).

View Source
const MinKeptBytes = 256

MinKeptBytes is the shortest a string value is cut to.

Variables

This section is empty.

Functions

func Attrs

func Attrs(ctx context.Context) []slog.Attr

Attrs returns a copy of the attributes in ctx, oldest first: those given to WithAttrs, then those added to the AttrSet of the unit of work (WithAttrSet). A later key wins in the line.

func Check

func Check(id identity.Identity) error

Check returns the usage failure of Resolve, for cli and lifecycle to refuse a start on a bad LOG_LEVEL or LOG_OUTPUT.

func Event

func Event(name string) slog.Attr

Event marks a record as the event name: log.LogAttrs(ctx, slog.LevelInfo, "", logging.Event("job.progress"), ...). The key event_name is fixed; this is the one way to set it.

func FromContext

func FromContext(ctx context.Context) *slog.Logger

FromContext returns the logger NewContext put in ctx, or slog.Default when there is none.

func New

func New(id identity.Identity, opts ...Option) *slog.Logger

New builds the logger for id. It never fails: when the log file cannot be opened the lines go to stderr as text, and the first line says why (log.fallback); a bad LOG_LEVEL or LOG_OUTPUT is ignored the same way. Check reports those as errors for a start-up refusal.

func NewContext

func NewContext(ctx context.Context, log *slog.Logger) context.Context

NewContext returns a context carrying log. lifecycle.Run sets it; cli.Execute reads it.

func WithAttrs

func WithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context

WithAttrs returns a context whose lines all carry attrs. The handler reads them on every record logged with that context, after the logger's own attributes and before the record's, so a record attribute with the same key wins. Calls accumulate: a child context keeps the parent's attributes and adds its own.

Types

type AttrSet

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

An AttrSet holds the attributes a unit of work gathers while it runs. work.Command and work.HTTP put one in the context with WithAttrSet; work.Add appends to it; every line written with that context carries what the set holds at that moment. A set made inside another unit keeps the outer set's attributes in front of its own.

func AttrSetFrom

func AttrSetFrom(ctx context.Context) *AttrSet

AttrSetFrom returns the AttrSet in ctx, or nil when no unit of work is open.

func WithAttrSet

func WithAttrSet(ctx context.Context) (context.Context, *AttrSet)

WithAttrSet returns a context carrying a new, empty AttrSet and the set itself.

func (*AttrSet) Add

func (s *AttrSet) Add(attrs ...slog.Attr)

Add appends attrs to the set. Safe for concurrent use.

func (*AttrSet) Attrs

func (s *AttrSet) Attrs() []slog.Attr

Attrs returns a copy of the set's attributes, the outer sets' first.

type Flat

type Flat struct {
	Key   string
	Value any
}

Flat is one key of a line as the line would carry it: Value is a string, int64, uint64, float64, bool or json.Number.

func Flatten

func Flatten(attrs ...slog.Attr) []Flat

Flatten applies the line rules of section 2 to attrs and returns the keys in line order: groups and objects flatten with dots, an array becomes its JSON text, durations and times become strings, a fixed key becomes attr.<key>, a later key replaces an earlier one. An error value becomes exception.type and exception.message. work uses it so a span carries the same attributes as the event line.

type Option

type Option func(*options)

Option changes how New builds the logger.

func Dir

func Dir(path string) Option

Dir sets the log folder instead of the one paths resolves.

func KeepDays

func KeepDays(n int) Option

KeepDays sets how many days of files the logger keeps (default 14); 0 keeps every file.

func Level

func Level(l slog.Level) Option

Level forces the minimum level over the environment; for tests.

func MaxFileBytes

func MaxFileBytes(n int64) Option

MaxFileBytes sets the size cap of a day's file (default 100 MB); 0 removes the cap.

func Now

func Now(now func() time.Time) Option

Now sets the clock; timestamps, file dates and retention follow it.

func Output

func Output(name string) Option

Output forces the output (OutputStdout, OutputFile or OutputStderr) over the environment.

func Writer

func Writer(w io.Writer) Option

Writer sends the JSON lines to w and nowhere else; for tests.

type Settings

type Settings struct {
	// Output is stdout, file or stderr; "writer" for a logger with the Writer option.
	Output string
	// OutputSource names what chose Output: the variable, the detection, "default", an option,
	// or the fallback with its reason.
	OutputSource string
	// Level is the minimum level written.
	Level slog.Level
	// LevelSource names the variable that set Level, or "default".
	LevelSource string
	// Dir is the log folder used when Output is file.
	Dir string
	// Err is the usage failure for a variable with a value outside its set, or nil. New
	// ignores the bad value and says so once; cli and lifecycle refuse to start.
	Err error
}

Settings is what the environment asks of the logger (Resolve) or what a logger does (SettingsOf), with the source of each choice, so doctor can print "where the logs go and why".

func Resolve

func Resolve(id identity.Identity) Settings

Resolve reads the environment for id by the order of contract.md section 5: <APP>_LOG_OUTPUT, LOG_OUTPUT, JOURNAL_STREAM matching stdout, stdout being the container's log, then the file; <APP>_LOG_LEVEL, LOG_LEVEL, then info.

func SettingsOf

func SettingsOf(log *slog.Logger) (s Settings, ok bool)

SettingsOf returns what a logger made by New does: the output it writes to and why, the level and its source, the folder. ok is false for a logger of another handler.

Jump to

Keyboard shortcuts

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