slogx

package module
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 15 Imported by: 3

README ΒΆ

log logo

go-slogx

Enhanced version of the go `slog` package which adds common handlers and extra features.






Table of Contents

πŸ‘οΈ Overview

go-slogx is based on the slog package in the Golang core as of version 1.21. This package adds numerous extra features that are not currently available in the standard package.

Please review the module documentation for details on how to properly the functions and classes contained in this module.

βœ… Requirements

This module is supported for Go v1.21 and later.

πŸ“ƒ License

This module is distributed under the MIT License.

❓ Questions, Issues and Feature Requests

If you have questions about this project, find a bug or wish to submit a feature request, please submit an issue.

Documentation ΒΆ

Overview ΒΆ

Package slogx is an enhanced version of the built-in log/slog package.

TODO: add full documentation across all packages with examples...

Index ΒΆ

Constants ΒΆ

View Source
const (
	LevelUnknown  = Level(-2147483648)
	LevelMin      = Level(-2147483647)
	LevelTrace    = Level(-8)
	LevelDebug    = Level(slog.LevelDebug)
	LevelInfo     = Level(slog.LevelInfo)
	LevelNotice   = Level(2)
	LevelWarn     = Level(slog.LevelWarn)
	LevelError    = Level(slog.LevelError)
	LevelFatal    = Level(12)
	LevelPanic    = Level(16)
	LevelMax      = Level(2147483646)
	LevelDisabled = Level(2147483647)
)

Extended log levels in addition to the standard ones.

View Source
const (
	// DefaultLoggingServiceName is used if a logging service is being stored in the context with no name.
	DefaultLoggingServiceName = "__default__"
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func ActiveLoggingServiceNameFromContext ΒΆ added in v0.6.3

func ActiveLoggingServiceNameFromContext(ctx context.Context) string

ActiveLogingServiceNameFromContext retrieves the active logging service name from the context, if it exists.

If multiple logging services are associated with a context, external libraries can use this function to retrieve the name of the appropriate logging service to retrieve for logging debug, error, etc. messages within their code.

If no active logging service name is set in the context, the default name is returned instead.

func ConsolidateAttrs ΒΆ

func ConsolidateAttrs(attrs []slog.Attr, group string, record slog.Record) []slog.Attr

ConsolidateAttrs combines the given attributes with attributes from the record, mapping the record attributes under the group, if not empty.

Attribute values are resolved during the consolidation and duplicate attributes are removed from the returned slice and any nested groups. If an attribute is specified more than once, the last one specified is used.

func ContextWithActiveLoggingService ΒΆ added in v0.6.3

func ContextWithActiveLoggingService(ctx context.Context, s LoggingService, name string) context.Context

ContextWithActiveLoggingService returns a new context with the given logging service stored with the given name and marks it as active.

If multiple logging services are associated with a context, external libraries can use ActiveLoggingServiceFromContext() to retrieve the appropriate logging service to use for logging debug, error, etc. messages within their code.

If no name is supplied, the default logging service name is used.

func ContextWithActiveLoggingServiceName ΒΆ added in v0.6.3

func ContextWithActiveLoggingServiceName(ctx context.Context, name string) context.Context

ContextWithActiveLoggingServiceName returns a new context with the name of the active logging service set.

If multiple logging services are associated with a context, external libraries can use ActiveLoggingServiceNameFromContext() to retrieve the appropriate logger name to then retrieve for logging debug, error, etc. messages within their code.

If no name is supplied, the default logging service name is used.

func ContextWithErrorAttrName ΒΆ added in v0.6.0

func ContextWithErrorAttrName(ctx context.Context, name string) context.Context

ContextWithErrorAttrName returns a new context with the given error attribute name stored.

If no name is supplied, the default attribute name is used instead.

func ContextWithFormatterOptions ΒΆ added in v0.5.1

func ContextWithFormatterOptions(ctx context.Context, opts any, name string) context.Context

ContextWithFormatterOptions copies the given context and returns a new context with the given formatter options stored in it with the given name.

func ContextWithHandler ΒΆ added in v0.4.1

func ContextWithHandler(ctx context.Context, h slog.Handler, name string) context.Context

ContextWithHandler copies the given context and returns a new context with the given handler stored in it with the given name.

func ContextWithHandlerLevel ΒΆ added in v0.5.1

func ContextWithHandlerLevel(ctx context.Context, level *LevelVar, name string) context.Context

ContextWithHandlerLevel copies the given context and returns a new context with the given handler log level stored in it with the given name.

func ContextWithHandlerOptions ΒΆ added in v0.5.0

func ContextWithHandlerOptions(ctx context.Context, opts any, name string) context.Context

ContextWithHandlerOptions copies the given context and returns a new context with the given handler options stored in it with the given name.

func ContextWithLoggingService ΒΆ added in v0.6.3

func ContextWithLoggingService(ctx context.Context, s LoggingService, name string) context.Context

ContextWithLoggingService copies the given context and returns a new context with the given logging service stored in it with the given name.

If no name is supplied, the default logging service name is used.

func Err ΒΆ

func Err(key string, value error) slog.Attr

Err returns an Attr for an error value.

func ErrX ΒΆ

func ErrX(key string, value errorx.Error) slog.Attr

ErrX returns an Attr for an extended error value.

func ErrorAttrNameFromContext ΒΆ added in v0.6.0

func ErrorAttrNameFromContext(ctx context.Context) string

ErrorAttrNameFromContext returns the attribute name to use for logging error messages.

func FlattenAttrs ΒΆ

func FlattenAttrs(attrs []slog.Attr) []slog.Attr

FlattenAttrs takes the given slice of attributes and recursively "flattens" groups changing the attribute keys to GROUP.KEY (or GROUP.GROUP.KEY in the case of nested groups).

func FormatterOptionsFromContext ΒΆ added in v0.5.1

func FormatterOptionsFromContext(ctx context.Context, name string) any

FormatterOptionsFromContext retrieves the formatter options stored in the given context with the given name, if it exists.

If the handler options cannot be found, nil is returned.

func HandlerFromContext ΒΆ added in v0.4.1

func HandlerFromContext(ctx context.Context, name string) slog.Handler

HandlerFromContext retrieves the handler stored in the given context with the given name, if it exists.

If the handler cannot be found, nil is returned.

func HandlerOptionsFromContext ΒΆ added in v0.5.0

func HandlerOptionsFromContext(ctx context.Context, name string) any

HandlerOptionsFromContext retrieves the handler options stored in the given context with the given name, if it exists.

If the handler options cannot be found, nil is returned.

func HttpRequest ΒΆ

func HttpRequest(key string, req *http.Request, sensitiveHeaders []string, sensitiveQueryParams []string) slog.Attr

HttpRequest returns an Attr for an HTTP request object.

func HttpResponse ΒΆ

func HttpResponse(key string, resp *http.Response, sensitiveHeaders []string) slog.Attr

HttpResponse returns an Attr for an HTTP response object.

func SetDefault ΒΆ added in v0.6.2

func SetDefault(l *Logger)

SetDefault replaces the default logger with the one supplied.

func Shutdown ΒΆ

func Shutdown(l *Logger, continueOnError bool) error

Shutdown will cleanup any open resources or pending goroutines being run in the handler(s) attached to the logger.

func SortAttrs ΒΆ

func SortAttrs(attrs []slog.Attr) []slog.Attr

SortAttrs sorts the given attributes and returns a slice sorted by attribute key.

Any nested attribute groups are sorted by attribute key as well.

func ToAttrMap ΒΆ

func ToAttrMap(attrs []slog.Attr) map[string]slog.Value

ToAttrMap converts the given attribute slice to a map of string/values.

This function does not recursively convert groups. Use FlattenAttrs to flatten the attribute list first.

func UniqAttrs ΒΆ

func UniqAttrs(attrs []slog.Attr) []slog.Attr

UniqAttrs removes duplicate attributes from the slice and any nested groups, resolving attribute values along the way.

If an attribute is duplicated, the last duplicate entry is used in the resulting slice.

Types ΒΆ

type Buffer ΒΆ

type Buffer []byte

Buffer is a simple type adapted from the built-in bytes.Buffer type.

func NewBuffer ΒΆ

func NewBuffer() *Buffer

New creates a new buffer.

func (*Buffer) Bytes ΒΆ

func (b *Buffer) Bytes() []byte

Bytes returns the bytes in the buffer.

func (*Buffer) Free ΒΆ

func (b *Buffer) Free()

Free returns buffers to the pool.

func (*Buffer) Len ΒΆ

func (b *Buffer) Len() int

Len returns the number of bytes currently in the buffer.

func (*Buffer) Reset ΒΆ

func (b *Buffer) Reset()

Reset clears the buffer.

func (*Buffer) String ΒΆ

func (b *Buffer) String() string

String returns the string stored by the buffer.

func (*Buffer) Write ΒΆ

func (b *Buffer) Write(p []byte) (int, error)

Write handles writing bytes to the buffer.

func (*Buffer) WriteByte ΒΆ

func (b *Buffer) WriteByte(c byte) error

WriteByte handles writing a single byte to the buffer.

func (*Buffer) WritePosInt ΒΆ

func (b *Buffer) WritePosInt(i int)

WritePosInt writes a non-negative integer to the buffer.

func (*Buffer) WritePosIntWidth ΒΆ

func (b *Buffer) WritePosIntWidth(i, width int)

WritePosIntWidth writes non-negative integer i to the buffer, padded on the left by zeroes to the given width.

Use a width of 0 to omit padding.

func (*Buffer) WriteString ΒΆ

func (b *Buffer) WriteString(s string)

Write string handles writing the string to the buffer.

type ErrorOptions ΒΆ added in v0.2.0

type ErrorOptions struct {
	// AdjustFrameCount indicates a number of frames to adjust the skip by when calling runtime.Callers. By default,
	// 3 frames are skipped when creating the record.
	AdjustFrameCount int

	// IncludeFileLine indicates whether or not to invoke runtime.Callers to get the program counter in order to retrieve
	// source file information.
	IncludeFileLine bool
}

ErrorOptions stores options for working with error records.

func NewErrorOptions ΒΆ added in v0.4.0

func NewErrorOptions() *ErrorOptions

NewErrorOptions creates a new object with default values.

func (*ErrorOptions) FromContext ΒΆ added in v0.4.0

func (o *ErrorOptions) FromContext(ctx context.Context) *ErrorOptions

FromContext retrieves the error options stored inside the context and replaces the current options with those.

If no options are found in the context, the object is left unchanged. The function returns the object itself as a convenient method for assigning the value.

func (*ErrorOptions) SaveToContext ΒΆ added in v0.4.0

func (o *ErrorOptions) SaveToContext(ctx context.Context) context.Context

SaveToContext stores the options within the given context and returns the new context.

type ErrorRecord ΒΆ added in v0.2.0

type ErrorRecord struct {
	// Error holds details of the extended error that occurred.
	Error errorx.Error

	// Record is the actual record which can be logged at a later time.
	Record slog.Record
}

ErrorRecord holds extended error information an a log record created when the error occurred.

The error can be logged at a later time using [LogRecord].

func NewErrorRecord ΒΆ added in v0.2.0

func NewErrorRecord(ctx context.Context, level slog.Leveler, msg string, err errorx.Error) *ErrorRecord

NewErrorRecord creates a new ErrorRecord object.

type Level ΒΆ

type Level int

Level is just an integer

func ParseLevel ΒΆ added in v0.6.2

func ParseLevel(l string) (Level, error)

ParseLevel parses a level string into an actual value.

func (Level) Level ΒΆ

func (l Level) Level() slog.Level

Level returns the level itself in order to implement the `Leveler` interface.

func (Level) MarshalJSON ΒΆ

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON marshals the level into a JSON string.

func (Level) MarshalText ΒΆ

func (l Level) MarshalText() ([]byte, error)

MarshalText marshals the level into a text string.

func (Level) ShortString ΒΆ

func (l Level) ShortString() string

Examples:

LevelWarn.String() => "WRN"
(LevelInfo+2).String() => "INF+2"

func (Level) String ΒΆ

func (l Level) String() string

String returns a name for the level.

If the level has a name, then that name in uppercase is returned. If the level is between named values, then an integer is appended to the uppercased name.

Examples:

LevelWarn.String() => "WARN"
(LevelInfo+2).String() => "INFO+2"

func (*Level) UnmarshalJSON ΒΆ

func (l *Level) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the given JSON string into the current level object.

func (*Level) UnmarshalText ΒΆ

func (l *Level) UnmarshalText(data []byte) error

UnmarshalText parses the given text string into the current level object.

type LevelVar ΒΆ added in v0.4.1

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

A LevelVar is a Level variable, to allow a Handler level to change dynamically.

It implements Leveler as well as a Set method, and it is safe for use by multiple goroutines. The zero LevelVar corresponds to LevelInfo.

func HandlerLevelFromContext ΒΆ added in v0.5.1

func HandlerLevelFromContext(ctx context.Context, name string) *LevelVar

HandlerLevelFromContext retrieves the handler log loeve stored in the given context with the given name, if it exists.

If the handler level cannot be found, nil is returned.

func NewLevelVar ΒΆ added in v0.4.1

func NewLevelVar(l Level) *LevelVar

NewLevelVar returns a new object with the given level set.

func (*LevelVar) Level ΒΆ added in v0.4.1

func (v *LevelVar) Level() Level

Level returns v's level.

func (*LevelVar) MarshalText ΒΆ added in v0.4.1

func (v *LevelVar) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.

func (*LevelVar) Set ΒΆ added in v0.4.1

func (v *LevelVar) Set(l Level)

Set sets v's level to l.

func (*LevelVar) String ΒΆ added in v0.4.1

func (v *LevelVar) String() string

func (*LevelVar) UnmarshalText ΒΆ added in v0.4.1

func (v *LevelVar) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler by calling Level.UnmarshalText.

type LevelVarHandler ΒΆ added in v0.5.0

type LevelVarHandler interface {
	slog.Handler

	// Level returns a pointer to the dynamic level variable.
	Level() *LevelVar
}

LevelVarHandler should be implemented by handlers that use a dynamic level via a LevelVar object.

type Logger ΒΆ

type Logger struct {
	*slog.Logger

	// AdjustFrameCount indicates a number of frames to adjust the skip by when calling runtime.Callers. By default,
	// 3 frames are skipped when creating the record.
	AdjustFrameCount int

	// IncludeFileLine indicates whether or not to invoke runtime.Callers to get the program counter in order to retrieve
	// source file information.
	IncludeFileLine bool
}

Logger is just a composition to be able to add functionality to the slog.Logger type.

func Default ΒΆ added in v0.3.1

func Default() *Logger

Default returns the default logger object.

func Nil ΒΆ added in v0.6.1

func Nil() *Logger

Nil returns a new "nil" logger which does not log anything, ever.

func Wrap ΒΆ

func Wrap(l *slog.Logger) *Logger

Wrap simply wraps the slog.Logger in an slogx.Logger object.

func (*Logger) Debug ΒΆ

func (l *Logger) Debug(msg string, args ...any)

Debug logs a message using DEBUG level.

func (*Logger) DebugContext ΒΆ

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

DebugContext logs a message using DEBUG level with context.

func (*Logger) Error ΒΆ

func (l *Logger) Error(msg string, args ...any)

Error logs a message using ERROR level.

func (*Logger) ErrorlContext ΒΆ

func (l *Logger) ErrorlContext(ctx context.Context, msg string, args ...any)

ErrorContext logs a message using ERROR level with context.

func (*Logger) Fatal ΒΆ

func (l *Logger) Fatal(msg string, args ...any)

Fatal logs a message using FATAL level.

func (*Logger) FatalContext ΒΆ

func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any)

FatalContext logs a message using FATAL level with context.

func (*Logger) Info ΒΆ

func (l *Logger) Info(msg string, args ...any)

Info logs a message using INFO level.

func (*Logger) InfoContext ΒΆ

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

InfoContext logs a message using INFO level with context.

func (*Logger) Log ΒΆ

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

Log simply logs a message at the given level.

func (*Logger) LogAttrs ΒΆ

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

LogAttrs is a more efficient way to log a message at any level while adding attributes.

func (*Logger) LogRecord ΒΆ added in v0.2.0

func (l *Logger) LogRecord(ctx context.Context, r slog.Record)

LogRecord simply logs the given pre-created record.

func (*Logger) Notice ΒΆ

func (l *Logger) Notice(msg string, args ...any)

Notice logs a message using NOTICE level.

func (*Logger) NoticeContext ΒΆ

func (l *Logger) NoticeContext(ctx context.Context, msg string, args ...any)

NoticeContext logs a message using NOTICE level with context.

func (*Logger) Panic ΒΆ

func (l *Logger) Panic(msg string, args ...any)

Panic logs a message using PANIC level.

func (*Logger) PanicContext ΒΆ

func (l *Logger) PanicContext(ctx context.Context, msg string, args ...any)

PanicContext logs a message using PANIC level with context.

func (*Logger) Shutdown ΒΆ

func (l *Logger) Shutdown(continueOnError bool) error

Shutdown will cleanup any open resources or pending goroutines being run in the handler(s) attached to the logger.

func (*Logger) Trace ΒΆ

func (l *Logger) Trace(msg string, args ...any)

Trace logs a message using TRACE level.

func (*Logger) TraceContext ΒΆ

func (l *Logger) TraceContext(ctx context.Context, msg string, args ...any)

TraceContext logs a message using TRACE level with context.

func (*Logger) Warn ΒΆ

func (l *Logger) Warn(msg string, args ...any)

Warn logs a message using WARN level.

func (*Logger) WarnContext ΒΆ

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

WarnContext logs a message using WARN level with context.

func (*Logger) With ΒΆ added in v0.6.0

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

With returns a new logger with the given attributes.

type LoggingService ΒΆ added in v0.6.3

type LoggingService interface {
	// Debug logs a message using DEBUG level.
	Debug(msg string, args ...any)

	// DebugContext logs a message using DEBUG level with context.
	DebugContext(ctx context.Context, msg string, args ...any)

	// Error logs a message using ERROR level.
	Error(msg string, args ...any)

	// ErrorContext logs a message using ERROR level with context.
	ErrorContext(ctx context.Context, msg string, args ...any)

	// Fatal logs a message using FATAL level.
	Fatal(msg string, args ...any)

	// FatalContext logs a message using FATAL level with context.
	FatalContext(ctx context.Context, msg string, args ...any)

	// Info logs a message using INFO level.
	Info(msg string, args ...any)

	// InfoContext logs a message using INFO level with context.
	InfoContext(ctx context.Context, msg string, args ...any)

	// Notice logs a message using NOTICE level.
	Notice(msg string, args ...any)

	// NoticeContext logs a message using NOTICE level with context.
	NoticeContext(ctx context.Context, msg string, args ...any)

	// Panic logs a message using PANIC level.
	Panic(msg string, args ...any)

	// PanicContext logs a message using PANIC level with context.
	PanicContext(ctx context.Context, msg string, args ...any)

	// Trace logs a message using TRACE level.
	Trace(msg string, args ...any)

	// TraceContext logs a message using TRACE level with context.
	TraceContext(ctx context.Context, msg string, args ...any)

	// Warn logs a message using WARN level.
	Warn(msg string, args ...any)

	// WarnContext logs a message using WARN level with context.
	WarnContext(ctx context.Context, msg string, args ...any)
}

LoggingService defines the interface a generic logging service should provide.

While it's ultimately up to the library calling these functions how to format the arg values of a function, it is highly recommended to use standard log/slog library attribute functions such as slog.String() or slog.Any() to construct key/value pairs or slog.Group() to create groups of key/value pairs.

Libraries which do not adhere to using log/slog library attribute functions, either as a sender or as a receiver, should clearly document how the arguments are expected.

func ActiveLoggingServiceFromContext ΒΆ added in v0.6.3

func ActiveLoggingServiceFromContext(ctx context.Context) LoggingService

ActiveLoggingServiceFromContext returns the active logging service from the context, if it exists.

If multiple logging services are associated with a context, external libraries can use this function to retrieve the name of the appropriate logging service to retrieve for logging debug, error, etc. messages within their code.

If no active logging service is set in the context, the logging service with the default name is returned. If no logging services are stored at all, nil is returned.

func LoggingServiceFromContext ΒΆ added in v0.6.3

func LoggingServiceFromContext(ctx context.Context, name string) LoggingService

LoggingServiceFromContext retrieves the logging service object stored in the given context with the given name, if it exists.

If no name is supplied, the default logging service name is used. If no matching logging service can be found, nil is returned instead.

type ShutdownableHandler ΒΆ

type ShutdownableHandler interface {
	slog.Handler

	// Shutdown should handle cleaning up any resources created by the handler (eg: closing file handles,
	// DB connections, etc.).
	Shutdown(bool) error
}

ShutdownableHandler should be implemented by handlers which allocate resources that need cleaning up before an application exits.

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

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