logging

package
v0.0.0-...-df8f258 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package logging provides structured logging configuration and handlers for slog.

Index

Constants

View Source
const (
	LevelTrace slog.Level = -8 // below Debug(-4)
	LevelFatal slog.Level = 12 // above Error(8)
	LevelPanic slog.Level = 16 // above Fatal
)

Custom slog.Level constants for extended severity levels.

Variables

This section is empty.

Functions

func ContextWithLogger

func ContextWithLogger(ctx context.Context, logger *slog.Logger) context.Context

ContextWithLogger stores a *slog.Logger in the context and returns a new context.

func CreateSlogLogger

func CreateSlogLogger(handler slog.Handler) *slog.Logger

CreateSlogLogger creates a *slog.Logger from the given slog.Handler. It returns the logger and an io.Closer for the file output (nil if no file logging).

func GetLoggingWriter

func GetLoggingWriter(cfg *Config, consoleWriter io.Writer) (io.WriteCloser, error)

GetLoggingWriter assembles an io.WriteCloser from the Config fields. It combines console and file writers as configured. Close is a no-op when file logging is not enabled.

func LogRecovery

func LogRecovery(logger *slog.Logger, msg string, r any)

LogRecovery logs a recovered panic with stack trace using the provided *slog.Logger.

func LoggerFromContext

func LoggerFromContext(ctx context.Context) *slog.Logger

LoggerFromContext extracts a *slog.Logger from the context. If no logger is found, it returns nil.

func LoggerFromContextOrDefault

func LoggerFromContextOrDefault(ctx context.Context, defaultLogger *slog.Logger) *slog.Logger

LoggerFromContextOrDefault extracts a *slog.Logger from the context. If no logger is found, it returns the provided default logger.

func NewDiscardLogger

func NewDiscardLogger() *slog.Logger

NewDiscardLogger returns a *slog.Logger that discards all output.

func NewLumberjackLogger

func NewLumberjackLogger(cfg *FileConfig) *lumberjack.Logger

NewLumberjackLogger creates a *lumberjack.Logger from a FileConfig and optionally rotates the log file on start.

func ParseSlogLevel

func ParseSlogLevel(levelStr string) (slog.Level, error)

ParseSlogLevel maps a level string to a slog.Level value. It is case-insensitive and supports all existing level strings: trace, debug, info, warn, warning, error, fatal, panic.

Types

type Config

type Config struct {
	Level        string      `koanf:"level"`
	Format       string      `koanf:"format"` // "plain" or "json"
	File         *FileConfig `koanf:"file"`
	NoConsoleLog bool        `koanf:"no_console_log"`
	// contains filtered or unexported fields
}

Config holds the overall logging configuration including level, format, and file output.

func (*Config) GetLoggingWriter

func (cfg *Config) GetLoggingWriter(consoleWriter io.Writer) (io.WriteCloser, error)

GetLoggingWriter delegates to the package-level GetLoggingWriter function.

func (*Config) SetDefaults

func (cfg *Config) SetDefaults()

SetDefaults applies default values for Level and Format if not already set.

func (*Config) Validate

func (cfg *Config) Validate() error

Validate checks that the Config has valid level and format values.

type FileConfig

type FileConfig struct {
	Disable       bool   `koanf:"disable"`
	Path          string `koanf:"path"`
	MaxSizeMB     int    `koanf:"max_size_mb"`
	MaxBackups    int    `koanf:"max_backups"`
	MaxAgeDays    int    `koanf:"max_age_days"`
	Compress      bool   `koanf:"compress"`
	RotateOnStart bool   `koanf:"rotate_on_start"`
}

FileConfig holds configuration for file-based log output with rotation settings.

func (*FileConfig) Validate

func (cfg *FileConfig) Validate() error

Validate checks that required FileConfig fields are set when file logging is enabled.

type SlogHandler

type SlogHandler struct {
	// contains filtered or unexported fields
}

SlogHandler is a custom slog.Handler that supports plain and JSON output formats, dynamic level control via slog.LevelVar, and concurrent-safe writes to any io.Writer.

func NewSlogHandler

func NewSlogHandler(out io.Writer, format string, opts *SlogHandlerOptions) *SlogHandler

NewSlogHandler creates a new SlogHandler writing to out in the specified format. If opts is nil, defaults to slog.LevelInfo.

func (*SlogHandler) Enabled

func (h *SlogHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (*SlogHandler) Handle

func (h *SlogHandler) Handle(_ context.Context, r slog.Record) error

Handle formats and writes the log record to the handler's writer.

func (*SlogHandler) WithAttrs

func (h *SlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new handler whose attributes include attrs.

func (*SlogHandler) WithGroup

func (h *SlogHandler) WithGroup(name string) slog.Handler

WithGroup returns a new handler with the given group name prepended to subsequent attrs.

type SlogHandlerOptions

type SlogHandlerOptions struct {
	// Level reports the minimum level to log. If nil, defaults to slog.LevelInfo.
	Level slog.Leveler
}

SlogHandlerOptions configures a SlogHandler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL