zlog

package
v2.17.3 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2025 License: MIT Imports: 13 Imported by: 5

Documentation

Overview

Package zlog lets you use golang structured logging (slog) with context. Add and retrieve logger to and from context. Add and retrieve attributes to and from context. Automatically read any custom context values, such as OpenTelemetry TraceID.

This package borrows code from package `github.com/veqryn/slog-context`. The reason of forking is that I want opinionated different API design, the code is simple, it's easy to maintain a new package.

Index

Constants

View Source
const ErrorKey = "error"

Variables

This section is empty.

Functions

func AppendAttrs added in v2.17.0

func AppendAttrs(parent context.Context, args ...any) context.Context

AppendAttrs adds the attribute arguments to the end of the group that will be appended to the end of the log record when it is handled. The attributes could be in a group or subgroup, if the log has used WithGroup at some point.

func ArgsToAttrSlice added in v2.17.0

func ArgsToAttrSlice(args ...any) []slog.Attr

ArgsToAttrSlice turns a slice of arguments, some of which pairs of primitives, some might be attributes already, into a slice of attributes.

func Debug

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

func Debugf

func Debugf(format string, args ...any)

Debugf logs a message at level slog.LevelDebug. Arguments are handled in the manner of fmt.Printf.

func Error

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

func Errorf

func Errorf(format string, args ...any)

Errorf logs a message at level slog.LevelError. Arguments are handled in the manner of fmt.Printf.

func ExtractAppended added in v2.17.0

func ExtractAppended(ctx context.Context, _ *slog.Record) slog.Attr

ExtractAppended is an AttrExtractor that returns the appended attributes stored in the context. The returned attr should not be modified in any way, doing so will cause a race condition.

func ExtractPrepended added in v2.17.0

func ExtractPrepended(ctx context.Context, _ *slog.Record) slog.Attr

ExtractPrepended is an AttrExtractor that returns the prepended attributes stored in the context. The returned attr should not be modified in any way, doing so will cause a race condition.

func Fatal

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

Fatal is equivalent to Error() followed by a call to os.Exit(1).

func Fatalf

func Fatalf(format string, args ...any)

Fatalf is equivalent to Errorf() followed by a call to os.Exit(1).

func Info

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

func Infof

func Infof(format string, args ...any)

Infof logs a message at level slog.LevelInfo. Arguments are handled in the manner of fmt.Printf.

func Log added in v2.17.0

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

func LogAttrs added in v2.17.0

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

func LogAttrsSkip added in v2.17.0

func LogAttrsSkip(ctx context.Context, skip int, level slog.Level, msg string, attrs ...slog.Attr)

func LogSkip added in v2.17.0

func LogSkip(ctx context.Context, skip int, level slog.Level, msg string, args ...any)

func NewCtx added in v2.17.0

func NewCtx(parent context.Context, logger *Logger) context.Context

NewCtx returns a copy of ctx with the logger attached. The parent context will be unaffected.

func NewMiddleware added in v2.17.0

func NewMiddleware(opts *HandlerOptions) func(slog.Handler) slog.Handler

NewMiddleware creates a slog.Handler middleware that conforms to github.com/samber/slog-multi.Middleware interface. It can be used with slogmulti methods such as Pipe to easily setup a pipeline of slog handlers:

slog.SetDefault(slog.New(slogmulti.
	Pipe(zlog.NewMiddleware(&zlog.HandlerOptions{})).
	Pipe(zlog.NewOverwriteMiddleware(&slogdedup.OverwriteHandlerOptions{})).
	Handler(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{})),
))

func PrependAttrs added in v2.17.0

func PrependAttrs(parent context.Context, args ...any) context.Context

PrependAttrs adds the attribute arguments to the end of the group that will be prepended to the start of the log record when it is handled. The attributes will be at the root level, and not in any groups.

func Print

func Print(args ...any)

Print logs a message at level slog.LevelInfo, or level detected from args, if it's enabled. It has same signature with log.Print, arguments are handled in the manner of fmt.Print.

func Printf

func Printf(format string, args ...any)

Printf logs a message at level slog.LevelInfo, or level detected from args, if it's enabled. It has same signature with log.Printf, arguments are handled in the manner of fmt.Printf.

func Println added in v2.1.0

func Println(args ...any)

Println logs a message at level slog.LevelInfo, or level detected from args, if it's enabled. It has same signature with log.Println, arguments are handled in the manner of fmt.Println.

func RedirectStdLog added in v2.4.0

func RedirectStdLog(l *Logger, attrs []slog.Attr)

func SetDefault added in v2.17.0

func SetDefault(l *Logger)

SetDefault makes l the default Logger. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged at LevelInfo using l's Handler.

func SetDevelopment

func SetDevelopment(level slog.Level)

SetDevelopment sets the default logger to use slogconsolehandler.Default as the underlying handler.

func Warn

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

func Warnf

func Warnf(format string, args ...any)

Warnf logs a message at level slog.LevelWarn. Arguments are handled in the manner of fmt.Printf.

Types

type AttrExtractor added in v2.17.0

type AttrExtractor func(ctx context.Context, record *slog.Record) slog.Attr

AttrExtractor is a function that retrieves or creates slog.Attr based on information/values found in the context.Context and the slog.Record.

type Handler added in v2.17.0

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

Handler is a slog.Handler middleware that will prepend and append attributes to log lines. The attributes are extracted out of the log record's context by the provided AttrExtractor functions. It passes the final record and attributes off to the next handler when finished.

func NewHandler added in v2.17.0

func NewHandler(next slog.Handler, opts *HandlerOptions) *Handler

NewHandler creates a slog.Handler middleware that will prepend and append attributes to log lines. The attributes are extracted out of the log record's context by the provided AttrExtractor functions. It passes the final record and attributes off to the next handler when finished. If opts is nil, the default options are used.

func (*Handler) Enabled added in v2.17.0

func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool

func (*Handler) Handle added in v2.17.0

func (h *Handler) Handle(ctx context.Context, r slog.Record) error

func (*Handler) WithAttrs added in v2.17.0

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

func (*Handler) WithGroup added in v2.17.0

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

type HandlerOptions added in v2.17.0

type HandlerOptions struct {
	// A list of functions to be called, each of which returns attributes
	// that should be prepended to the start of every log line with the context.
	// If left nil, the default ExtractPrepended function will be used.
	Prependers []AttrExtractor

	// A list of functions to be called, each of which will return attributes
	// that should be appended to the end of every log line with the context.
	// If left nil, the default ExtractAppended function will be used.
	Appenders []AttrExtractor
}

HandlerOptions are options for a Handler

type Logger

type Logger = slog.Logger

func Default added in v2.17.0

func Default() *Logger

Default returns the default Logger.

func FromCtx added in v2.17.0

func FromCtx(ctx context.Context) *Logger

FromCtx returns the logger associated with the ctx. If no logger is associated, or the logger or ctx is nil, slog.Default() is returned. This function will convert a logr.Logger to a *slog.Logger only if necessary.

func With

func With(ctx context.Context, args ...any) *Logger

func WithError added in v2.17.0

func WithError(ctx context.Context, err error, args ...any) *Logger

func WithGroup added in v2.17.0

func WithGroup(ctx context.Context, group string, args ...any) *Logger

Directories

Path Synopsis
internal
test
Package test provides useful test helpers that can be used in multiple packages.
Package test provides useful test helpers that can be used in multiple packages.

Jump to

Keyboard shortcuts

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