Documentation ¶
Overview ¶
Example ¶
// Create a handler that writes to stdout. h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTimeAttr}) // Set the prefix for all log messages based on attribute "service". prefixed := NewHandler(h, &HandlerOptions{ PrefixKeys: []string{"service"}, PrefixFormatter: DefaultPrefixFormatter, }) logger := slog.New(prefixed) logger.Info("Hello World!") logger.Info("Hello World!", "service", "billing") logger.With("service", "database").Error("Connection error")
Output: level=INFO msg="Hello World!" level=INFO msg="billing > Hello World!" level=ERROR msg="database > Connection error"
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ColorizePrefix ¶
ColorizePrefix wraps a prefix formatter function to colorize its output with cyan ANSI codes.
func DefaultPrefixFormatter ¶
DefaultPrefixFormatter constructs a prefix string by joining all detected prefix values using ":". A " > " suffix is added at the end of the prefix string.
Types ¶
type Handler ¶
type Handler struct { Next slog.Handler // The next log handler in the chain. // contains filtered or unexported fields }
Handler is a custom slog handler that wraps another slog.Handler to prepend a prefix to the log messages. The prefix is sourced from the log record's attributes using the keys specified in PrefixKeys.
func NewHandler ¶
func NewHandler(next slog.Handler, opts *HandlerOptions) *Handler
NewHandler creates a new prefix logging handler. The new handler will prepend a prefix sourced from the log record's attributes to each log message before passing the record to the next handler.
type HandlerOptions ¶
type HandlerOptions struct { PrefixKeys []string // A list of keys used to fetch prefix values from the log record. // PrefixFormatter is a function to format the prefix of the log record. // If it's not set, the DefaultPrefixFormatter with ColorizePrefix wrapper is used. PrefixFormatter func(prefixes []slog.Value) string }
Click to show internal directories.
Click to hide internal directories.