Documentation
¶
Overview ¶
Package log provides a configurable constructor for the standard slog.Logger, allowing for easy setup using the functional options pattern.
It simplifies the creation of a structured logger by abstracting away the handler setup and providing flexible options for setting the level, format, and output from common types like strings.
Usage: ¶
Create a logger that outputs JSON at a debug level to standard error:
logger := log.New(
log.WithLevel("debug"),
log.WithFormat("json"),
log.WithWriter(os.Stderr),
log.WithAddSource(true), // Include file and line number.
)
slog.SetDefault(logger)
slog.Debug("This is a debug message")
Index ¶
Constants ¶
const ( DefaultLevel = slog.LevelInfo DefaultAddSource = false DefaultFormat = FormatText )
Default configuration values for a new logger.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Format ¶
type Format uint8
Format defines the log output format, such as JSON or plain text.
func ParseFormat ¶
ParseFormat converts a case-insensitive string into a Format. Valid inputs are "text" and "json". It returns an error for any other value.
type Option ¶
type Option func(*config)
Option defines a function that modifies the logger configuration.
func WithAddSource ¶
WithAddSource configures the logger to include the source code position (file and line number) in each log entry.
Note that this has a performance cost and should be used judiciously, often enabled only during development or at debug levels.
func WithFormat ¶
WithFormat sets the log output format. It accepts either a Format constant (FormatText or FormatJSON) or a case-insensitive string ("text" or "json") as handled by ParseFormat. If an invalid string or type is provided, the option is a no-op.
func WithLevel ¶
WithLevel sets the minimum log level. It accepts either a slog.Level constant (e.g., slog.LevelDebug) or a case-insensitive string (e.g., "debug") as handled by ParseLevel. If an invalid string or type is provided, the option is a no-op.
func WithWriter ¶
WithWriter returns an Option that sets the output destination for the logs. If the provided io.Writer is nil, it is ignored.