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 ¶
- Constants
- Variables
- func CaptureStdLog(l *slog.Logger, level slog.Level)
- func Emit(ctx context.Context, l *slog.Logger, d *Def, args ...any)
- func HTTPErrorLog(l *slog.Logger, listener string) *log.Logger
- func JoinContext(fns ...func(context.Context, []slog.Attr) []slog.Attr) func(context.Context, []slog.Attr) []slog.Attr
- func LevelName(l slog.Level) string
- func MatchBus(r *Record, _ *Levels) bool
- func MatchLevels(r *Record, lv *Levels) bool
- func MatchSecurity(r *Record, _ *Levels) bool
- func Module(name string) *slog.Logger
- func ParseLevel(s string) (slog.Level, error)
- func PprofLabels(ctx context.Context, dst []slog.Attr) []slog.Attr
- func Register(defs ...*Def)
- func StdLogger(l *slog.Logger, level slog.Level) *log.Logger
- type AsyncOutput
- type Config
- type Console
- type Def
- type Encoder
- type Entry
- type Field
- type Flusher
- type Format
- type JSONEncoder
- type Levels
- func (l *Levels) Clear(module string)
- func (l *Levels) Of(module string) slog.Level
- func (l *Levels) Override(module string, level slog.Level, ttl time.Duration) error
- func (l *Levels) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (l *Levels) Set(spec string) error
- func (l *Levels) String() string
- type Logs
- func (l *Logs) Attach(r Route) (detach func(), err error)
- func (l *Logs) Close()
- func (l *Logs) Configure(c Config) error
- func (l *Logs) Flush()
- func (l *Logs) Handler() slog.Handler
- func (l *Logs) Levels() *Levels
- func (l *Logs) Memory() *Memory
- func (l *Logs) Module(name string) *slog.Logger
- func (l *Logs) Reopen()
- func (l *Logs) SetLogSecrets(on bool)
- type Match
- type Memory
- type Output
- type PrettyEncoder
- type Query
- type Record
- type Redacted
- type Reopener
- type Rotating
- type Rotation
- type Route
- type Sampling
- type Subscription
- type TextEncoder
Examples ¶
Constants ¶
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.
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.
const LevelOff = slog.Level(1 << 20)
LevelOff is above every level: nothing is written.
const LevelTrace = slog.Level(-8)
LevelTrace is below debug, for per-packet detail.
Variables ¶
var Default = New()
Default is the Logs that Module uses.
var ErrTooManyOverrides = errors.New("slogx: too many level overrides")
ErrTooManyOverrides is returned by Override beyond Config.MaxOverrides modules.
Functions ¶
func CaptureStdLog ¶
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 ¶
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 ¶
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 ¶
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 MatchLevels ¶
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 ¶
MatchSecurity takes the events defined as security events, whatever the levels.
func ParseLevel ¶
ParseLevel reads one level name: trace, debug, info, warn, error, off, and the syslog-style names and numbers earlier configurations used.
func PprofLabels ¶
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.
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 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 ¶
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.
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 )
type JSONEncoder ¶
type JSONEncoder struct{}
JSONEncoder writes one JSON object per line, with the keys of TextEncoder; numbers and booleans keep their type.
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) Override ¶
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.
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 ¶
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 ¶
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 ¶
Handler returns a handler with no module, for slog.SetDefault or a library that takes one.
func (*Logs) 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) Reopen ¶
func (l *Logs) Reopen()
Reopen reopens the log files, after an external rotation (SIGHUP).
func (*Logs) SetLogSecrets ¶
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 ¶
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 MatchMinLevel ¶
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 (*Memory) Subscribe ¶
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
type Output ¶
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 ¶
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".
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.
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].
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 ¶
OpenRotating opens the file of c, creating its directory.
func (*Rotating) Close ¶
Close closes the file and waits for compression and pruning; writes after it fail.
func (*Rotating) Write ¶
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 ¶
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) Dropped ¶
func (s *Subscription) Dropped() uint64
Dropped reports how many entries did not fit in the queue.
Source Files
¶
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. |