log

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 7 Imported by: 0

README

Logger

Usage

slog
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
	Level: slog.LevelInfo,
}))

log.SetDefault(logger)

logger.InfoContext(ctx, "user created",
	"user_id", userID,
	"service.name", "helloworld",
)
Global logger

Common global helpers are still available for gradual migration. The signatures now mirror slog: the first argument is the message, followed by key/value pairs or slog.Attr values.

log.Info("started")
log.Info("listening", "addr", addr)
log.Info("service started", "service.name", "helloworld", "service.version", "v1.0.0")
log.InfoContext(ctx, "user created", "user_id", userID)
Builder

log.NewHandler builds a default handler. log.NewLogger wraps an existing handler with Forge decorators. Attach fixed service attrs with logger.With.

logger := log.NewLogger(
	slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
	}),
	log.WithFilter(log.WithFilterKey("password")), // redact sensitive keys
).With(
	slog.String("service.id", id),
	slog.String("service.name", name),
	slog.String("service.version", version),
)
log.SetDefault(logger)
Context attrs

Attach attributes to a context.Context and they will flow through any ctx-aware log call automatically.

ctx = log.ContextWithAttrs(ctx, slog.String("request_id", id))
log.InfoContext(ctx, "handling request")
OpenTelemetry
import (
	otel "github.com/sylphylabs/forge/contrib/otel/log"
	"github.com/sylphylabs/forge/log"
)

logger := log.NewLogger(otel.NewHandler("helloworld"))
log.SetDefault(logger)

The github.com/sylphylabs/forge/contrib/otel/log handler bridges slog records to OpenTelemetry Logs. Use the core log builder when you need Forge logger options:

import (
	"log/slog"

	otel "github.com/sylphylabs/forge/contrib/otel/log"
	"github.com/sylphylabs/forge/log"
)

logger := log.NewLogger(
	otel.NewHandler("helloworld"),
	log.WithFilter(log.WithFilterKey("password")),
).With(slog.String("service.name", "helloworld"))

Documentation

Overview

Package log builds structured loggers on the standard library's log/slog.

Forge defines no logger interface of its own: components accept and return *log/slog.Logger. NewHandler builds a composed handler with the package's defaults — text or JSON encoding (WithFormat), a minimum level (WithLevel), context-attribute extraction, and key redaction (WithFilter, WithFilterKey) — and NewLogger wraps any handler, including one from another package, in the same decorators.

ContextWithAttrs attaches attributes to a context; every record logged with that context through a composed handler carries them, which is how per-request values such as trace IDs reach log output without threading a logger through every call. SetDefault installs a logger as both this package's and slog's process default; the package-level helpers (With, WithGroup, Handler, Enabled) mirror the slog API on that default.

The OpenTelemetry bridge lives in the separate contrib/otel/log module; see docs/agent/observability.md for wiring logs into traces.

Index

Constants

View Source
const LevelKey = slog.LevelKey

LevelKey is logger level key.

Variables

This section is empty.

Functions

func AttrsFromContext

func AttrsFromContext(ctx context.Context) []slog.Attr

AttrsFromContext returns the attrs previously attached with ContextWithAttrs. The returned slice must not be mutated by callers.

func ContextWithAttrs

func ContextWithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context

ContextWithAttrs returns a copy of ctx with the given attrs attached. Attrs already on the context are preserved; new attrs are appended.

Use NewLogger or NewHandler so these attrs are automatically added to every record handled with that context.

func Debug

func Debug(msg string, args ...any)

Debug logs at debug level. Signature mirrors slog.Logger.Debug.

func DebugContext

func DebugContext(ctx context.Context, msg string, args ...any)

DebugContext logs at debug level with the provided context.

func Default

func Default() *slog.Logger

Default returns the default logger.

func Enabled

func Enabled(ctx context.Context, level Level) bool

Enabled reports whether the default logger emits log records at the given context and level. It mirrors slog.Logger.Enabled on the default logger.

func Error

func Error(msg string, args ...any)

Error logs at error level. Signature mirrors slog.Logger.Error.

func ErrorContext

func ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext logs at error level with the provided context.

func Handler

func Handler() slog.Handler

Handler returns the default logger's handler. It mirrors slog.Logger.Handler on the default logger.

func Info

func Info(msg string, args ...any)

Info logs at info level. Signature mirrors slog.Logger.Info.

func InfoContext

func InfoContext(ctx context.Context, msg string, args ...any)

InfoContext logs at info level with the provided context.

func Log

func Log(ctx context.Context, level Level, msg string, args ...any)

Log emits a record at the given level. It mirrors slog.Logger.Log on the default logger.

func LogAttrs

func LogAttrs(ctx context.Context, level Level, msg string, attrs ...slog.Attr)

LogAttrs emits a typed-attr record at the given level. It mirrors slog.Logger.LogAttrs on the default logger.

func NewHandler

func NewHandler(opts ...Option) slog.Handler

NewHandler builds a composed slog.Handler with forge defaults:

  • text encoding to stderr at LevelInfo
  • context attrs from ContextWithAttrs are merged in

Additional decorators are layered as configured.

func NewLogger

func NewLogger(handler slog.Handler, opts ...Option) *slog.Logger

NewLogger returns a slog logger backed by handler with forge decorators applied.

func SetDefault

func SetDefault(logger *slog.Logger)

SetDefault sets the default logger used by the package-level helpers and by slog.Default.

func Warn

func Warn(msg string, args ...any)

Warn logs at warn level. Signature mirrors slog.Logger.Warn.

func WarnContext

func WarnContext(ctx context.Context, msg string, args ...any)

WarnContext logs at warn level with the provided context.

func With

func With(args ...any) *slog.Logger

With returns a logger that includes the given attributes in each output operation. It mirrors slog.Logger.With on the default logger.

func WithGroup

func WithGroup(name string) *slog.Logger

WithGroup returns a logger that starts a group. It mirrors slog.Logger.WithGroup on the default logger.

Types

type Extractor

type Extractor func(context.Context) []slog.Attr

Extractor extracts attrs from a log call context.

type FilterOption

type FilterOption func(*filterConfig)

FilterOption configures filtering in WithFilter.

func WithFilterFunc

func WithFilterFunc(fn func(ctx context.Context, record slog.Record) bool) FilterOption

WithFilterFunc drops records for which fn returns true. fn is evaluated after key redaction.

func WithFilterKey

func WithFilterKey(keys ...string) FilterOption

WithFilterKey redacts the values of attributes whose key matches any of the provided keys. Keys may be leaf names ("password") or dotted group paths ("user.password").

type Format

type Format int

Format selects the encoding used by the default handler builder.

const (
	// FormatText writes records using [slog.NewTextHandler].
	FormatText Format = iota
	// FormatJSON writes records using [slog.NewJSONHandler].
	FormatJSON
)

type Level

type Level = slog.Level

Level is a logger level.

const (
	// LevelDebug is logger debug level.
	LevelDebug Level = slog.LevelDebug
	// LevelInfo is logger info level.
	LevelInfo Level = slog.LevelInfo
	// LevelWarn is logger warn level.
	LevelWarn Level = slog.LevelWarn
	// LevelError is logger error level.
	LevelError Level = slog.LevelError
)

func ParseLevel

func ParseLevel(s string) (Level, error)

ParseLevel parses a level string into a logger Level value. It accepts the forms slog's slog.Level.UnmarshalText accepts, such as "INFO" and "ERROR+2", in any case. It returns an error when s names no known level.

type LevelVar

type LevelVar = slog.LevelVar

LevelVar is a variable log level.

type Leveler

type Leveler = slog.Leveler

Leveler provides a log level.

type Option

type Option func(*handlerConfig)

Option configures NewHandler and the decorators applied by NewLogger.

func WithAddSource

func WithAddSource(b bool) Option

WithAddSource toggles inclusion of the source file/line.

func WithExtractor

func WithExtractor(extractors ...Extractor) Option

WithExtractor appends attrs extracted from each log call context.

func WithFilter

func WithFilter(opts ...FilterOption) Option

WithFilter applies the provided filter options on top of the composed handler.

func WithFormat

func WithFormat(f Format) Option

WithFormat selects between text and JSON encoding. Defaults to FormatText.

func WithLevel

func WithLevel(l Leveler) Option

WithLevel sets the minimum level for the base handler.

func WithReplaceAttr

func WithReplaceAttr(fn func(groups []string, a slog.Attr) slog.Attr) Option

WithReplaceAttr installs a custom ReplaceAttr on the base handler.

func WithWriter

func WithWriter(w io.Writer) Option

WithWriter sets the destination writer for the base handler. Defaults to os.Stderr.

Jump to

Keyboard shortcuts

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