slogx

package module
v0.0.0-...-4910a20 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: MIT Imports: 27 Imported by: 0

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 ΒΆ

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 ΒΆ

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 ΒΆ

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 ΒΆ

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 "error" is used instead.

func ContextWithFailoverHandlerOptions ΒΆ

func ContextWithFailoverHandlerOptions(ctx context.Context, opts FailoverHandlerOptions) context.Context

ContextWithFailoverHandlerOptions adds the options to the given context and returns the new context.

func ContextWithFileHandlerOptions ΒΆ

func ContextWithFileHandlerOptions(ctx context.Context, opts FileHandlerOptions) context.Context

ContextWithFileHandlerOptions adds the options to the given context and returns the new context.

func ContextWithHandler ΒΆ

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 ΒΆ

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 ContextWithIncludeCallerInRecord ΒΆ

func ContextWithIncludeCallerInRecord(ctx context.Context, include bool) context.Context

ContextWithIncludeCallerInRecord returns a new context with the given caller information flag value stored.

func ContextWithLoggingService ΒΆ

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 ContextWithMultiHandlerOptions ΒΆ

func ContextWithMultiHandlerOptions(ctx context.Context, opts MultiHandlerOptions) context.Context

ContextWithMultiHandlerOptions adds the options to the given context and returns the new context.

func ContextWithPipeHandlerOptions ΒΆ

func ContextWithPipeHandlerOptions(ctx context.Context, opts PipeHandlerOptions) context.Context

ContextWithPipeHandlerOptions adds the options to the given context and returns the new context.

func ContextWithRecordCallerFrameCountAdjustment ΒΆ

func ContextWithRecordCallerFrameCountAdjustment(ctx context.Context, count int) context.Context

ContextWithRecordCallerFrameCountAdjustment returns a new context with the given frame count adjustment stored.

If a record is not being created directly at the point in which the event or error occurred, you may need to adjust the frame count to get an accurate location of where the actual event occurred.

func ContextWithRoundRobinHandlerOptions ΒΆ

func ContextWithRoundRobinHandlerOptions(ctx context.Context, opts RoundRobinHandlerOptions) context.Context

ContextWithRoundRobinHandlerOptions adds the options to the given context and returns the new context.

func DefaultConsoleFormatter ΒΆ

func DefaultConsoleFormatter(colorize bool) *consoleFormatter

DefaultConsoleFormatter returns a console formatter with typical defaults already set.

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 ΒΆ

func ErrorAttrNameFromContext(ctx context.Context) string

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

If the value has not been stored in the context or it is not a string, the default attribute "error" is returned.

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 FormatAttrDefault ΒΆ

func FormatAttrDefault(ctx context.Context, level slog.Leveler, group string, key string,
	value slog.Value) (string, slog.Value, error)

FormatAttrDefault simply returns the key and value as-is without being modified in any way.

This function never returns an error.

func FormatFileLineValueDefault ΒΆ

func FormatFileLineValueDefault(ctx context.Context, level slog.Leveler, line uint) (string, error)

func FormatFileNameValueDefault ΒΆ

func FormatFileNameValueDefault(ctx context.Context, level slog.Leveler, name string) (string, error)

func FormatLevelValueDefault ΒΆ

func FormatLevelValueDefault(ctx context.Context, level slog.Leveler) (string, error)

FormatLevelValueDefault is a default level formatter which simply shortens the level to 3 letters.

Standard slogx levels are formatted using their ShortString() function while any other level is shortened to the first three characters and capitalized.

func FormatMessageValueDefault ΒΆ

func FormatMessageValueDefault(ctx context.Context, level slog.Leveler, msg string) (string, error)

func FormatMethodValueDefault ΒΆ

func FormatMethodValueDefault(ctx context.Context, level slog.Leveler, method string) (string, error)

func FormatSourceValueDefault ΒΆ

func FormatSourceValueDefault(ctx context.Context, l slog.Leveler, pc uintptr) (string, error)

func FormatTimestampValueDefault ΒΆ

func FormatTimestampValueDefault(ctx context.Context, level slog.Leveler, t time.Time) (string, error)

FormatTimestampValueDefault is a default source code location formatter which returns the time as the UTC time in RFC3339 format.

func HandlerFromContext ΒΆ

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 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 IncludeCallerInRecordFromContext ΒΆ

func IncludeCallerInRecordFromContext(ctx context.Context) (bool, error)

IncludeCallerInRecordFromContext returns from the context whether or not to include caller information in a record.

If the value has not been stored in the context or is not a boolean, the default value of false is returned along with an error.

func NewConditionalHandlerBuilder ΒΆ

func NewConditionalHandlerBuilder() *conditionalHandlerBuilder

NewConditionalHandlerBuilder creates a new conditionalHandlerBuilder object.

func NewConsoleFormatterBuilder ΒΆ

func NewConsoleFormatterBuilder() *consoleFormatterBuilder

NewConsoleFormatterBuilder creates a new consoleFormatterBuilder object.

func NewConsoleHandler ΒΆ

func NewConsoleHandler(opts ConsoleHandlerOptions) *consoleHandler

NewConsoleHandler creates a new handler object.

func NewErrorEventRecordBuilder ΒΆ

func NewErrorEventRecordBuilder(err errorx.Error) *errorEventRecordBuilder

NewErrorEventRecordBuilder creates a new errorEventRecordBuilder object.

By default, the timestamp on the record is set to the current time and date, the level is set to slog.LevelError, the message is set to the string returned by the error's Error() function and the program counter is set to 0.

func NewErrorEventRecordBuilderWithContext ΒΆ

func NewErrorEventRecordBuilderWithContext(ctx context.Context, err errorx.Error) *errorEventRecordBuilder

NewErrorEventRecordBuilder creates a new errorEventRecordBuilder object.

By default, the timestamp on the record is set to the current time and date, the level is set to slog.LevelError, the message is set to the string returned by the error's Error() function and the program counter is set to 0 unless caller information is enabled as indicated by the given context.

func NewEventRecordBuilder ΒΆ

func NewEventRecordBuilder(l slog.Leveler, msg string) *eventRecordBuilder

NewEventRecordBuilder creates a new eventRecordBuilder object.

By default, the timestamp on the record is set to the current time and date and the program counter is set to 0.

func NewEventRecordBuilderWithContext ΒΆ

func NewEventRecordBuilderWithContext(ctx context.Context, l slog.Leveler, msg string) *eventRecordBuilder

NewEventRecordBuilderWithContext creates a new eventRecordBuilder object with context.

By default, the timestamp on the record is set to the current time and date and the program counter is set to 0 unless caller information is enabled as indicated by the given context.

func NewFailoverHandler ΒΆ

func NewFailoverHandler(opts FailoverHandlerOptions, handlers ...slog.Handler) *failoverHandler

NewFailoverHandler creates a new handler object.

func NewFileHandler ΒΆ

func NewFileHandler(opts FileHandlerOptions) (*fileHandler, error)

NewFileHandler creates a new handler object.

func NewHTTPHandler ΒΆ

func NewHTTPHandler(opts HTTPHandlerOptions) (*httpHandler, error)

NewHTTPHandler creates a new handler object.

func NewHandlerCondition ΒΆ

func NewHandlerCondition(f HandlerConditionFn) *handlerCondition

NewHandlerCondition creates a new handlerCondition object.

func NewJSONHandler ΒΆ

func NewJSONHandler(opts JSONHandlerOptions) *jsonHandler

NewJSONHandler creates a new handler object.

func NewMultiHandler ΒΆ

func NewMultiHandler(opts MultiHandlerOptions, handler ...slog.Handler) *multiHandler

NewMultiHandler creates a new handler object.

func NewPipeHandler ΒΆ

func NewPipeHandler(opts PipeHandlerOptions, next slog.Handler) *pipeHandler

NewPipeHandler creates a new object.

func NewRoundRobinHandler ΒΆ

func NewRoundRobinHandler(opts RoundRobinHandlerOptions, handlers ...slog.Handler) *roundRobinHandler

NewRoundRobinHandler creates a new handler object.

func RecordCallerFrameCountAdjustmentFromContext ΒΆ

func RecordCallerFrameCountAdjustmentFromContext(ctx context.Context) (int, error)

RecordCallerFrameCountAdjustmentFromContext returns from the context the number of additional frames to skip when obtaining caller information to store in a record.

If the value has not been stored or is not an integer, the default value of 0 is returned along with an error.

func SetDefault ΒΆ

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 BufferFormatter ΒΆ

type BufferFormatter interface {
	// FormatRecord should take the data from the record and format it as needed, storing it in the returned buffer.
	FormatRecord(ctx context.Context, t time.Time, l Level, pc uintptr, msg string, attrs []slog.Attr) (*Buffer, error)
}

BufferFormatter describes the interface a formatter which outputs a record to a buffer must implement.

type ColorBufferFormatter ΒΆ

type ColorBufferFormatter interface {
	BufferFormatter

	// IsColorized should return whether or not the formatter uses colorized output.
	IsColorized() bool
}

ColorBufferFormatter describes the interface a formatter which supports colorized text and outputs a record to a buffer must implement.

type ConsoleHandlerOptions ΒΆ

type ConsoleHandlerOptions struct {
	// Level is the minimum log level to write to the handler.
	//
	// If this is nil, it defaults to LevelInfo.
	Level *LevelVar

	// RecordFormatter specifies the formatter to use to format the record before writing it to the writer.
	//
	// If no formatter is supplied, a colorized DefaultConsoleFormatter is used to format the output.
	RecordFormatter ColorBufferFormatter

	// Writer is where to write the output to.
	//
	// By default, messages are written to os.Stdout if not supplied.
	Writer io.Writer
}

ConsoleHandlerOptions holds the options for the console handler.

func DefaultConsoleHandlerOptions ΒΆ

func DefaultConsoleHandlerOptions() ConsoleHandlerOptions

DefaultConsoleHandlerOptions returns a default set of options for the handler.

func GetConsoleHandlerOptionsFromContext ΒΆ

func GetConsoleHandlerOptionsFromContext(ctx context.Context) *ConsoleHandlerOptions

GetConsoleHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

func (*ConsoleHandlerOptions) AddToContext ΒΆ

func (o *ConsoleHandlerOptions) AddToContext(ctx context.Context) context.Context

AddToContext adds the options to the given context and returns the new context.

type ErrorEventRecord ΒΆ

type ErrorEventRecord interface {
	EventRecord
	error

	// ErrorX should return the extended error object associated with the event.
	Errorx() errorx.Error
}

ErrorEventRecord defines an object that is used for creating an error event.

This interface implements the EventRecord and standard error interfaces.

type EventRecord ΒΆ

type EventRecord interface {
	// Attrs should return the attributes associated with the event.
	Attrs() []slog.Attr

	// Level should return the level of the event.
	Level() slog.Leveler

	// Message should return the message associated with the event.
	Message() string

	// PC should return the program counter indicating the location in the source code at which the event occurred.
	PC() uintptr

	// Record should return an slog.Record representation of the event.
	Record() slog.Record

	// Source should return the file, line and function name in which the event occurred.
	Source() slog.Source

	// Timestamp should return the timestamp of the event.
	Timestamp() time.Time
}

EventRecord defines an object that is used for creating an event which is usually logged and contains a timestamp, message, level and optionally a location in the source code where the event occurred and additional attributes.

type FailoverHandlerOptions ΒΆ

type FailoverHandlerOptions struct {
	// ContinueOnError determines whether or not to continue if an error occurs running middleware.
	ContinueOnError bool
}

FailoverHandlerOptions holds the options available when creating the failoverHandler object.

func DefaultFailoverHandlerOptions ΒΆ

func DefaultFailoverHandlerOptions() FailoverHandlerOptions

DefaultFailoverHandlerOptions returns a default set of options for the handler.

func FailoverHandlerOptionsFromContext ΒΆ

func FailoverHandlerOptionsFromContext(ctx context.Context) *FailoverHandlerOptions

FailoverHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

type FileHandlerOptions ΒΆ

type FileHandlerOptions struct {
	// DirMode is the mode to use when creating directories.
	//
	// By default, directories will be created with mode 0755.
	DirMode fs.FileMode

	// Filename is the name of the log file to write to.
	//
	// This is a required option.
	Filename string

	// FileMode is the mode to use when creating log files.
	//
	// By default, files will be created with mode 0640.
	FileMode fs.FileMode

	// Level is the minimum log level to write to the handler.
	//
	// If this is nil, it defaults to LevelInfo.
	Level *LevelVar

	// MaxFileCount indicates the maximum number of log files to keep, including the active log file.
	//
	// By default, this is set to 5. If this value is negative, an unlimited number of files will be kept.
	MaxFileCount int

	// MaxFileSize indicates the maximum size of any log file, in bytes. Once a file reaches this size,
	// it will be rotated automatically.
	//
	// By default, the maximum file size will be 10MB (10000000 bytes). If this value is negative, the file will
	// never be rotated.
	MaxFileSize int64

	// RecordFormatter specifies the formatter to use to format the record before sending it to Slack.
	//
	// If no formatter is supplied, DefaultJSONFormatter is used to format the output.
	RecordFormatter BufferFormatter
}

FileHandlerOptions holds options for the file handler.

func DefaultFileHandlerOptions ΒΆ

func DefaultFileHandlerOptions() FileHandlerOptions

DefaultFileHandlerOptions returns a default set of options for the handler.

func FileHandlerOptionsFromContext ΒΆ

func FileHandlerOptionsFromContext(ctx context.Context) *FileHandlerOptions

FileHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

type FormatAttrFn ΒΆ

type FormatAttrFn func(context.Context, slog.Leveler, string, string, slog.Value) (string, slog.Value, error)

FormatAttrFn is used to format the key and value for a particular attribute in the record.

The group name will be an empty string for attributes not nested within a group. Otherwise, the group will be populated with the name of the group to which the attribute belongs. If an attribue is nested in multiple groups, each group is separated by a single period (.) character (eg: group1.group2.group3).

The function should return the formatted key and value. The value passed to this function should be resolved by the handler prior to being passed. The value returned by the function will NOT be resolved again, so if this function creates a value which needs resolving, it should be resolved prior to returning it.

type FormatCustomPlaceholderFn ΒΆ

type FormatCustomPlaceholderFn func(ctx context.Context, placeholder string, l slog.Leveler, r slog.Record) (string, error)

type FormatFileLineValueFn ΒΆ

type FormatFileLineValueFn func(context.Context, slog.Leveler, uint) (string, error)

type FormatFileNameValueFn ΒΆ

type FormatFileNameValueFn func(context.Context, slog.Leveler, string) (string, error)

type FormatLevelValueFn ΒΆ

type FormatLevelValueFn func(context.Context, slog.Leveler) (string, error)

FormatLevelValueFn is used to format the record's level.

type FormatMessageValueFn ΒΆ

type FormatMessageValueFn func(context.Context, slog.Leveler, string) (string, error)

FormatMessageValueFn is used to format the message.

type FormatMethodValueFn ΒΆ

type FormatMethodValueFn func(context.Context, slog.Leveler, string) (string, error)

type FormatSourceValueFn ΒΆ

type FormatSourceValueFn func(ctx context.Context, l slog.Leveler, pc uintptr) (string, error)

type FormatTimestampValueFn ΒΆ

type FormatTimestampValueFn func(context.Context, slog.Leveler, time.Time) (string, error)

FormatTimestampValueFn is used to format the time the record was created.

type HTTPHandlerOptions ΒΆ

type HTTPHandlerOptions struct {
	// ContentType is the mime type to pass to the HTTP endpoint.
	//
	// By default, this is set to application/json as it is assumed the message being sent will be in JSON format.
	ContentType string

	// EnableAsync will execute the Handle() function in a separate goroutine.
	//
	// When async is enabled, you should be sure to call the Shutdown() function or use the Shutdown()
	// function to ensure all goroutines are finished and any pending records have been written.
	EnableAsync bool

	// HTTPClient allows for the use of a custom HTTP client for posting the message to the HTTP listener.
	//
	// If nil, a default resty client is used.
	HTTPClient *resty.Client

	// Level is the minimum log level to write to the handler.
	//
	// If this is nil, it defaults to LevelInfo.
	Level *LevelVar

	// RecordFormatter specifies the formatter to use to format the record before sending it to the HTTP listener.
	//
	// If no formatter is supplied, DefaultJSONFormatter is used to format the output.
	RecordFormatter BufferFormatter

	// URL is the URL of the HTTP endpoint to post the message to.
	//
	// This is a required option.
	URL string
}

HTTPHandlerOptions holds the options for the HTTP handler.

func DefaultHTTPHandlerOptions ΒΆ

func DefaultHTTPHandlerOptions() HTTPHandlerOptions

DefaultHTTPHandlerOptions returns a default set of options for the handler.

func GetHTTPHandlerOptionsFromContext ΒΆ

func GetHTTPHandlerOptionsFromContext(ctx context.Context) *HTTPHandlerOptions

GetHTTPHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

func (*HTTPHandlerOptions) AddToContext ΒΆ

func (o *HTTPHandlerOptions) AddToContext(ctx context.Context) context.Context

AddToContext adds the options to the given context and returns the new context.

type HandlerConditionFn ΒΆ

type HandlerConditionFn func(ctx context.Context, r slog.Record) bool

HandlerConditionFn is called to determine whether or not the given record should be logged.

type JSONHandlerOptions ΒΆ

type JSONHandlerOptions struct {
	// Level is the minimum log level to write to the handler.
	//
	// If this is nil, it defaults to LevelInfo.
	Level *LevelVar

	// RecordFormatter specifies the formatter to use to format the record before writing it to the writer.
	//
	// If no formatter is supplied, DefaultJSONFormatter is used to format the output.
	RecordFormatter BufferFormatter

	// Writer is where to write the output to.
	//
	// By default, messages are written to os.Stdout if not supplied.
	Writer io.Writer
}

JSONHandlerOptions holds the options for the JSON handler.

func DefaultJSONHandlerOptions ΒΆ

func DefaultJSONHandlerOptions() JSONHandlerOptions

DefaultJSONHandlerOptions returns a default set of options for the handler.

func GetJSONHandlerOptionsFromContext ΒΆ

func GetJSONHandlerOptionsFromContext(ctx context.Context) *JSONHandlerOptions

GetJSONHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

func (*JSONHandlerOptions) AddToContext ΒΆ

func (o *JSONHandlerOptions) AddToContext(ctx context.Context) context.Context

AddToContext adds the options to the given context and returns the new context.

type Level ΒΆ

type Level int

Level is just an integer

func ParseLevel ΒΆ

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 ΒΆ

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 ΒΆ

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 ΒΆ

func NewLevelVar(l Level) *LevelVar

NewLevelVar returns a new object with the given level set.

func (*LevelVar) Level ΒΆ

func (v *LevelVar) Level() Level

Level returns v's level.

func (*LevelVar) MarshalText ΒΆ

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

MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.

func (*LevelVar) Set ΒΆ

func (v *LevelVar) Set(l Level)

Set sets v's level to l.

func (*LevelVar) String ΒΆ

func (v *LevelVar) String() string

func (*LevelVar) UnmarshalText ΒΆ

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

UnmarshalText implements encoding.TextUnmarshaler by calling Level.UnmarshalText.

type LevelVarHandler ΒΆ

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

	// IncludeCaller indicates whether or not to include caller details when creating the record to be logged.
	//
	// If a log function includes a context with its own include caller flag, it will override this value.
	IncludeCallerInRecord bool

	// RecordCallerFrameCountAdjustment indicates a number of additional frames skip when retrieving caller
	// information to add to a record.
	//
	// If a log function includes a context with its own adjustment count set, it will override this value.
	RecordCallerFrameCountAdjustment int
}

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

func Default ΒΆ

func Default() *Logger

Default returns the default logger object.

func Nil ΒΆ

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, attrs ...slog.Attr)

Debug logs a message using DEBUG level.

func (*Logger) DebugWithContext ΒΆ

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

DebugWithContext logs a message using DEBUG level with context.

func (*Logger) Error ΒΆ

func (l *Logger) Error(msg string, attrs ...slog.Attr)

Error logs a message using ERROR level.

func (*Logger) ErrorWithContext ΒΆ

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

ErrorWithContext logs a message using ERROR level with context.

func (*Logger) Fatal ΒΆ

func (l *Logger) Fatal(msg string, attrs ...slog.Attr)

Fatal logs a message using FATAL level.

func (*Logger) FatalWithContext ΒΆ

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

FatalWithContext logs a message using FATAL level with context.

func (*Logger) Info ΒΆ

func (l *Logger) Info(msg string, attrs ...slog.Attr)

Info logs a message using INFO level.

func (*Logger) InfoWithContext ΒΆ

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

InfoWithContext logs a message using INFO level with context.

func (*Logger) Log ΒΆ

func (l *Logger) Log(level Level, msg string, attrs ...slog.Attr)

Log simply logs a message at the given level.

func (*Logger) LogRecord ΒΆ

func (l *Logger) LogRecord(r EventRecord)

LogRecord simply logs the given pre-created record.

func (*Logger) LogRecordWithContext ΒΆ

func (l *Logger) LogRecordWithContext(ctx context.Context, r EventRecord)

LogRecordWithContext simply logs the given pre-created record with context.

func (*Logger) LogWithContext ΒΆ

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

LogWithContext simply logs a message at the given level with context.

func (*Logger) Notice ΒΆ

func (l *Logger) Notice(msg string, attrs ...slog.Attr)

Notice logs a message using NOTICE level.

func (*Logger) NoticeWithContext ΒΆ

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

NoticeWithContext logs a message using NOTICE level with context.

func (*Logger) Panic ΒΆ

func (l *Logger) Panic(msg string, attrs ...slog.Attr)

Panic logs a message using PANIC level.

func (*Logger) PanicWithContext ΒΆ

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

PanicWithContext 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, attrs ...slog.Attr)

Trace logs a message using TRACE level.

func (*Logger) TraceWithContext ΒΆ

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

TraceWithContext logs a message using TRACE level with context.

func (*Logger) Warn ΒΆ

func (l *Logger) Warn(msg string, attrs ...slog.Attr)

Warn logs a message using WARN level.

func (*Logger) WarnWithContext ΒΆ

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

WarnWithContext logs a message using WARN level with context.

func (*Logger) With ΒΆ

func (l *Logger) With(attrs ...slog.Attr) *Logger

With returns a new logger with the given attributes.

type LoggingService ΒΆ

type LoggingService interface {
	// Log simply should log a message at the given level.
	Log(level slog.Leveler, msg string, attrs ...slog.Attr)

	// Log simply should log a message at the given level with context.
	LogWithContext(ctx context.Context, level slog.Leveler, msg string, attrs ...slog.Attr)

	// LogRecord should log the given pre-created record.
	LogRecord(r EventRecord)

	// LogRecord should log the given pre-created record with context
	LogRecordWithContext(ctx context.Context, r EventRecord)
}

LoggingService defines the interface a generic logging service should provide.

The slogx.Logger object implements this interface.

func ActiveLoggingServiceFromContext ΒΆ

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 ΒΆ

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 MultiHandlerOptions ΒΆ

type MultiHandlerOptions struct {
	// ContinueOnError determines whether or not to continue logging to handlers to if an error occurs while writing to
	// a particular handler or running any middleware.
	ContinueOnError bool

	// EnableAsync will execute the Handle() function in a separate goroutine in case there are slow handlers being
	// used for writing the record.
	//
	// Typically, a specific handler should implement its own async writing if it is slow, but this is a fallback in
	// case it does not.
	//
	// When async is enabled, you should be sure to call the Shutdown() function or use the Shutdown()
	// function to ensure all goroutines are finished and any pending records have been written.
	EnableAsync bool
}

MultiHandlerOptions holds the options available when creating the multiHandler object.

func DefaultMultiHandlerOptions ΒΆ

func DefaultMultiHandlerOptions() MultiHandlerOptions

DefaultMultiHandlerOptions returns a default set of options for the handler.

func MultiHandlerOptionsFromContext ΒΆ

func MultiHandlerOptionsFromContext(ctx context.Context) *MultiHandlerOptions

MultiHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

type PipeHandlerFn ΒΆ

type PipeHandlerFn func(context.Context, slog.Record) (slog.Record, error)

PipeHandlerFn should take the clone of the given record, modify it as needed and return the modified version.

type PipeHandlerOptions ΒΆ

type PipeHandlerOptions struct {
	// ContinueOnError determines whether or not to continue logging to handlers to if an error occurs while running any
	// of the pipe functions.
	ContinueOnError bool

	// PipeFns defines the list of functions to pipe the record through before passing it onto the next handler.
	PipeFns []PipeHandlerFn
}

PipeHandlerOptions holds the options for the pipe handler.

func DefaultPipeHandlerOptions ΒΆ

func DefaultPipeHandlerOptions() PipeHandlerOptions

DefaultPipeHandlerOptions returns a default set of options for the handler.

func PipeHandlerOptionsFromContext ΒΆ

func PipeHandlerOptionsFromContext(ctx context.Context) *PipeHandlerOptions

PipeHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options is returned instead.

type RoundRobinHandlerOptions ΒΆ

type RoundRobinHandlerOptions struct {
	// ContinueOnError determines whether or not to continue if an error occurs running middleware.
	ContinueOnError bool
}

RoundRobinHandlerOptions holds the options available when creating the roundRobinHandler object.

func DefaultRoundRobinHandlerOptions ΒΆ

func DefaultRoundRobinHandlerOptions() RoundRobinHandlerOptions

DefaultRoundRobinHandlerOptions returns a default set of options for the handler.

func RoundRobinHandlerOptionsFromContext ΒΆ

func RoundRobinHandlerOptionsFromContext(ctx context.Context) *RoundRobinHandlerOptions

RoundRobinHandlerOptionsFromContext retrieves the options from the context.

If the options are not set in the context, a set of default options 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(ctx context.Context, continueOnError bool) error
}

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

Jump to

Keyboard shortcuts

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