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
- func ActiveLoggingServiceNameFromContext(ctx context.Context) string
- func ConsolidateAttrs(attrs []slog.Attr, group string, record slog.Record) []slog.Attr
- func ContextWithActiveLoggingService(ctx context.Context, s LoggingService, name string) context.Context
- func ContextWithActiveLoggingServiceName(ctx context.Context, name string) context.Context
- func ContextWithErrorAttrName(ctx context.Context, name string) context.Context
- func ContextWithFormatterOptions(ctx context.Context, opts any, name string) context.Context
- func ContextWithHandler(ctx context.Context, h slog.Handler, name string) context.Context
- func ContextWithHandlerLevel(ctx context.Context, level *LevelVar, name string) context.Context
- func ContextWithHandlerOptions(ctx context.Context, opts any, name string) context.Context
- func ContextWithLoggingService(ctx context.Context, s LoggingService, name string) context.Context
- func Err(key string, value error) slog.Attr
- func ErrX(key string, value errorx.Error) slog.Attr
- func ErrorAttrNameFromContext(ctx context.Context) string
- func FlattenAttrs(attrs []slog.Attr) []slog.Attr
- func FormatterOptionsFromContext(ctx context.Context, name string) any
- func HandlerFromContext(ctx context.Context, name string) slog.Handler
- func HandlerOptionsFromContext(ctx context.Context, name string) any
- func HttpRequest(key string, req *http.Request, sensitiveHeaders []string, ...) slog.Attr
- func HttpResponse(key string, resp *http.Response, sensitiveHeaders []string) slog.Attr
- func SetDefault(l *Logger)
- func Shutdown(l *Logger, continueOnError bool) error
- func SortAttrs(attrs []slog.Attr) []slog.Attr
- func ToAttrMap(attrs []slog.Attr) map[string]slog.Value
- func UniqAttrs(attrs []slog.Attr) []slog.Attr
- type Buffer
- func (b *Buffer) Bytes() []byte
- func (b *Buffer) Free()
- func (b *Buffer) Len() int
- func (b *Buffer) Reset()
- func (b *Buffer) String() string
- func (b *Buffer) Write(p []byte) (int, error)
- func (b *Buffer) WriteByte(c byte) error
- func (b *Buffer) WritePosInt(i int)
- func (b *Buffer) WritePosIntWidth(i, width int)
- func (b *Buffer) WriteString(s string)
- type ErrorOptions
- type ErrorRecord
- type Level
- type LevelVar
- type LevelVarHandler
- type Logger
- func (l *Logger) Debug(msg string, args ...any)
- func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Error(msg string, args ...any)
- func (l *Logger) ErrorlContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Fatal(msg string, args ...any)
- func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Info(msg string, args ...any)
- func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
- func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...slog.Attr)
- func (l *Logger) LogRecord(ctx context.Context, r slog.Record)
- func (l *Logger) Notice(msg string, args ...any)
- func (l *Logger) NoticeContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Panic(msg string, args ...any)
- func (l *Logger) PanicContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Shutdown(continueOnError bool) error
- func (l *Logger) Trace(msg string, args ...any)
- func (l *Logger) TraceContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Warn(msg string, args ...any)
- func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) With(args ...any) *Logger
- type LoggingService
- type ShutdownableHandler
Constants ΒΆ
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.
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
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 ΒΆ
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
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
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
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
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
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
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
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 ErrorAttrNameFromContext ΒΆ added in v0.6.0
ErrorAttrNameFromContext returns the attribute name to use for logging error messages.
func FlattenAttrs ΒΆ
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
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
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
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 ΒΆ
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 ΒΆ
Shutdown will cleanup any open resources or pending goroutines being run in the handler(s) attached to the logger.
func SortAttrs ΒΆ
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 ΒΆ
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.
Types ΒΆ
type Buffer ΒΆ
type Buffer []byte
Buffer is a simple type adapted from the built-in bytes.Buffer type.
func (*Buffer) WritePosInt ΒΆ
WritePosInt writes a non-negative integer to the buffer.
func (*Buffer) WritePosIntWidth ΒΆ
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 ΒΆ
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
ParseLevel parses a level string into an actual value.
func (Level) MarshalJSON ΒΆ
MarshalJSON marshals the level into a JSON string.
func (Level) MarshalText ΒΆ
MarshalText marshals the level into a text string.
func (Level) 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 ΒΆ
UnmarshalJSON parses the given JSON string into the current level object.
func (*Level) UnmarshalText ΒΆ
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
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
NewLevelVar returns a new object with the given level set.
func (*LevelVar) MarshalText ΒΆ added in v0.4.1
MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.
func (*LevelVar) UnmarshalText ΒΆ added in v0.4.1
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 Nil ΒΆ added in v0.6.1
func Nil() *Logger
Nil returns a new "nil" logger which does not log anything, ever.
func (*Logger) DebugContext ΒΆ
DebugContext logs a message using DEBUG level with context.
func (*Logger) ErrorlContext ΒΆ
ErrorContext logs a message using ERROR level with context.
func (*Logger) FatalContext ΒΆ
FatalContext logs a message using FATAL level with context.
func (*Logger) InfoContext ΒΆ
InfoContext logs a message using INFO level with context.
func (*Logger) LogAttrs ΒΆ
LogAttrs is a more efficient way to log a message at any level while adding attributes.
func (*Logger) NoticeContext ΒΆ
NoticeContext logs a message using NOTICE level with context.
func (*Logger) PanicContext ΒΆ
PanicContext logs a message using PANIC level with context.
func (*Logger) Shutdown ΒΆ
Shutdown will cleanup any open resources or pending goroutines being run in the handler(s) attached to the logger.
func (*Logger) TraceContext ΒΆ
TraceContext logs a message using TRACE level with context.
func (*Logger) WarnContext ΒΆ
WarnContext logs a message using WARN level with context.
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.