Documentation
¶
Overview ¶
Package gologger provides configurable slog loggers, context attributes and public handler extension points. New never changes the process default logger.
Index ¶
- Variables
- func Error(err error) slog.Attr
- func SetDefault(log *Log)
- func WithValue(ctx context.Context, attr slog.Attr) context.Context
- type Config
- type Log
- type Logger
- type Middleware
- type Option
- func WithAdditionalHandlers(handlers ...OptionHandler) Option
- func WithClosers(closers ...io.Closer) Option
- func WithHandler(handler slog.Handler) Option
- func WithLevel(level slog.Leveler) Option
- func WithMiddleware(middleware ...Middleware) Option
- func WithReplaceAttr(replace func([]string, slog.Attr) slog.Attr) Option
- func WithWriter(writer io.Writer) Option
- type OptionHandler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var LogLevel = legacyLevel()
LogLevel controls legacy NewLogger and Discard loggers. Use WithLevel for new code. Mutate it through Set; replacing this pointer is unsupported.
Functions ¶
func SetDefault ¶
func SetDefault(log *Log)
SetDefault explicitly installs log as both the package and slog default. The host remains responsible for closing any previous logger. log must be non-nil.
Types ¶
type Config ¶
type Config struct {
Env string `` //nolint:lll // it's config
/* 133-byte string literal not displayed */
Rate float64 `toml:"rate" long:"log-rate" env:"LOG_RATE" value-default:"0" validate:"min=0,max=1"`
Level string `toml:"level" long:"log-level" env:"LOG_LEVEL" value-default:"info" validate:"required,oneof=debug info warn error"` //nolint:lll // it's config
AddSource bool `toml:"add_source" long:"add-source" env:"LOG_ADD_SOURCE" validate:"boolean"`
AddVerbose bool `toml:"add_verbose" long:"add-verbose" env:"LOG_ADD_VERBOSE" validate:"boolean"`
JSON bool `toml:"json" long:"log-json" env:"LOG_JSON" validate:"boolean"`
Output string `toml:"output" long:"log-output" env:"LOG_OUTPUT"`
}
Config is the portable logging configuration. Tags describe configuration and environment mappings; New does not read the environment itself.
func (Config) IsProduction ¶
type Log ¶
Log embeds slog.Logger and shares resource ownership with WithNamed/WithAttrs children. Close the root after all users have stopped logging.
func Default ¶
func Default() *Log
Default returns this package's default without changing slog.Default.
func Discard ¶
func Discard(handlers ...OptionHandler) *Log
Discard returns a no-op logger with optional additional destinations. Additional handlers receive the legacy shared LogLevel.
func DiscardJSONWithWriter ¶
func DiscardTextWithWriter ¶
func New ¶
New builds an independent logger. The default is JSON on stdout at WARN; local/development uses pretty output unless Config.JSON is true. It starts no goroutines and does not change LogLevel or slog.Default.
Example ¶
package main
import (
"context"
"log/slog"
"os"
"github.com/assurrussa/gologger"
)
func main() {
log, err := gologger.New(gologger.Config{Level: "info"},
gologger.WithWriter(os.Stdout),
gologger.WithReplaceAttr(func(_ []string, attr slog.Attr) slog.Attr {
if attr.Key == slog.TimeKey {
return slog.Attr{}
}
return attr
}))
if err != nil {
panic(err)
}
defer func() {
if err := log.Close(); err != nil {
panic(err)
}
}()
ctx := gologger.WithValue(context.Background(), slog.String("request_id", "r-1"))
log.WithNamed("worker").InfoContext(ctx, "ready")
}
Output: {"level":"INFO","msg":"ready","name":"worker","request_id":"r-1"}
func NewLogger ¶
func NewLogger(cfg Config, handlers ...OptionHandler) (*Log, error)
NewLogger configures the global logger with a shared level, WARN fallback and local pretty output. Prefer New for independent instances. Use New followed by SetDefault only when process wiring requires it.
func (*Log) Close ¶
Close flushes and closes owned resources once. Every caller receives the same result, including concurrent calls through derived loggers. Borrowed writers and handlers are never closed. Logging after Close is unsupported.
type Logger ¶
type Logger interface {
Handler() slog.Handler
DebugContext(ctx context.Context, msg string, args ...any)
InfoContext(ctx context.Context, msg string, args ...any)
WarnContext(ctx context.Context, msg string, args ...any)
ErrorContext(ctx context.Context, msg string, args ...any)
LogAttrs(ctx context.Context, level slog.Level, msg string, attrs ...slog.Attr)
WithNamed(name string) Logger
WithAttrs(attrs ...slog.Attr) Logger
}
Logger is the consumer-facing logging contract. Implementations may wrap any slog.Handler; lifecycle ownership remains with the concrete logger's creator.
type Middleware ¶
Middleware wraps a handler. It must preserve slog's concurrency and derivation contracts.
type Option ¶
type Option func(*options)
Option configures a new logger without changing process defaults.
func WithAdditionalHandlers ¶
func WithAdditionalHandlers(handlers ...OptionHandler) Option
WithAdditionalHandlers adds destinations alongside the primary handler.
func WithClosers ¶
WithClosers transfers cleanup responsibility on successful construction only. Close/Flush calls each closer once in reverse order; a closer must flush its own buffers. Derived loggers share the same cleanup state.
func WithHandler ¶
WithHandler replaces the built-in console handler. The supplied handler owns its own level, source and attribute configuration. File output remains additive.
func WithLevel ¶
WithLevel overrides Config.Level without mutating the supplied level. A *slog.LevelVar permits runtime changes shared only by explicitly wired loggers.
func WithMiddleware ¶
func WithMiddleware(middleware ...Middleware) Option
WithMiddleware wraps the combined destinations after context enrichment and before sampling. Middleware executes in the supplied order, first outermost.
func WithReplaceAttr ¶
WithReplaceAttr configures built-in handlers and additional handler factories.
func WithWriter ¶
WithWriter replaces stdout for the built-in handler. The caller owns the writer and must flush/close it, or explicitly transfer ownership through WithClosers.
type OptionHandler ¶
type OptionHandler func(*slog.HandlerOptions) slog.Handler
OptionHandler builds an additional handler using the configured slog options. A nil result skips this handler. Each factory receives its own options copy.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
handlers
|
|
|
slogpretty
Package slogpretty formats slog's JSON output for local interactive use.
|
Package slogpretty formats slog's JSON output for local interactive use. |