journal/journslog/handler_option.go

84 lines
2.6 KiB
Go

package journslog
import (
"context"
"log/slog"
"time"
"src.lwithers.me.uk/go/journal"
)
// HandlerOption is passed to [NewHandler] to control the behaviour of the
// newly-created [JournalHandler].
type HandlerOption func(jh *JournalHandler)
// WithHandlerOptions applies an [slog.HandlerOptions] to a newly-created
// [JournalHandler].
//
// If AddSource is set, then the widley-recognised journal attributes
// CODE_FILE, CODE_LINE and CODE_FUNC will be added to each journal entry.
func WithHandlerOptions(opts slog.HandlerOptions) HandlerOption {
return func(jh *JournalHandler) {
jh.addSource = opts.AddSource
if opts.Level == nil {
jh.minLevel = slog.LevelInfo
} else {
jh.minLevel = opts.Level
}
jh.replaceAttr = opts.ReplaceAttr
}
}
// WithLevelMapper allows control over how [slog.Level] values are mapped to
// [journal.Priority] values.
func WithLevelMapper(levelMapper LevelMapper) HandlerOption {
return func(jh *JournalHandler) {
jh.levelMapper = levelMapper
}
}
// WithKeyMapper allows control over how attribute string keys are mapped to
// journal keys.
func WithKeyMapper(keyMapper KeyMapper) HandlerOption {
return func(jh *JournalHandler) {
jh.keyMapper = keyMapper
}
}
// WithConn uses the given [journal.Conn] connection object, rather than the
// global default.
func WithConn(conn *journal.Conn) HandlerOption {
return func(jh *JournalHandler) {
jh.conn = conn
}
}
// WithLevelFromContext supplies a function which can optionally extract a
// more-specific minimum log level to use for a given message from a
// [context.Context]. If the supplied levelFromContext returns true in its
// second argument, then its first argument is used as the minimum level.
// Otherwise, the handler's default minimum level will be used.
func WithLevelFromContext(levelFromContext func(context.Context) (slog.Level, bool)) HandlerOption {
return func(jh *JournalHandler) {
jh.levelFromContext = levelFromContext
}
}
// WithAttrsFromContext supplies a function which can optionally extract
// attributes from a given [context.Context] value. It may return nil or a
// zero-length slice.
func WithAttrsFromContext(attrsFromContext func(context.Context) []slog.Attr) HandlerOption {
return func(jh *JournalHandler) {
jh.attrsFromContext = attrsFromContext
}
}
// WithAttrsFromTime supplies a function which can optionally map the Time
// field from an [slog.Record] onto zero or more attributes. The supplied
// function is never called with a zero [time.Time].
func WithAttrsFromTime(attrsFromTime func(time.Time) []slog.Attr) HandlerOption {
return func(jh *JournalHandler) {
jh.attrsFromTime = attrsFromTime
}
}