Skip to main content

slogx

import "github.com/go-softwarelab/common/pkg/slogx"

Package slogx provides utility functions and helpers to complement the Go slog package. It offers convenient methods for creating and configuring loggers for both production and testing environments. Additionally, it includes tools to facilitate testing of logging output.

This package also provides a set of functions for creating slog.Args in a standardized way for some of the most popular use cases, helping ensure consistency and clarity in structured logging across your codebase.

The main goal of this package is to simplify logger setup, reduce boilerplate, and enhance the ergonomics of consistent structured logging throughout application code and tests.

Constants

const (

// ServiceKey is a predefined constant used as a key for identifying services or components in structured logging.
ServiceKey = "service"
// ComponentKey is a predefined constant used as a key for identifying components in structured logging.
ComponentKey = "component"
// ErrorKey is a predefined constant used as a key for identifying errors in structured logging.
ErrorKey = "error"
// UserIDKey is a predefined constant used as a key for identifying user IDs in structured logging.
UserIDKey = "userId"
)

LevelNone is a special log level that disables all logging.

const LevelNone slog.Level = math.MaxInt

Child

func Child(logger *slog.Logger, serviceName string) *slog.Logger

Child returns a new logger with the specified service name added to its attributes. If the provided logger is nil, it uses the default slog logger as the base.

ChildForComponent

func ChildForComponent(logger *slog.Logger, componentName string) *slog.Logger

ChildForComponent returns a new logger with the specified component name added to its attributes. If the provided logger is nil, it uses the default slog logger as the base. It is strongly recommended to use slogx.Child instead of this function. However, if you need to distinguish components (such as library tools) from services, this function can be useful.

Component

func Component(componentName string) slog.Attr

Component creates a slog.Attr with the predefined ComponentKey and the given componentName. This is a conventional attribute for marking loggers for components in an application. It is strongly recommended to use slogx.Service instead of this function. However, if you need to distinguish components (such as library tools) from services, this function can be useful.

DefaultIfNil

func DefaultIfNil(logger *slog.Logger) *slog.Logger

DefaultIfNil returns the default slog.Logger if the given logger is nil.

Error

func Error(err error) slog.Attr

Error returns a slog.Attr containing the provided error message under the "error" key.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
err := fmt.Errorf("test error")
fmt.Println(slogx.Error(err))
}

Output

error=test error

IsDebug

func IsDebug(logger *slog.Logger) bool

IsDebug checks if the provided logger has the debug level enabled.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
debugLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelDebug).
WritingToConsole().
WithTextFormat().
Logger()

infoLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelInfo).
WritingToConsole().
WithTextFormat().
Logger()

fmt.Println(slogx.IsDebug(debugLogger))
fmt.Println(slogx.IsDebug(infoLogger))

}

Output

true
false

IsError

func IsError(logger *slog.Logger) bool

IsError checks if the provided logger is enabled at the error logging level.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
errorLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelError).
WritingToConsole().
WithTextFormat().
Logger()

infoLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelInfo).
WritingToConsole().
WithTextFormat().
Logger()

noneLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelNone).
WritingToConsole().
WithTextFormat().
Logger()

fmt.Println(slogx.IsError(errorLogger))
fmt.Println(slogx.IsError(infoLogger))
fmt.Println(slogx.IsError(noneLogger))

}

Output

true
true
false

IsInfo

func IsInfo(logger *slog.Logger) bool

IsInfo checks if the provided logger has the info level enabled.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
infoLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelInfo).
WritingToConsole().
WithTextFormat().
Logger()

warnLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelWarn).
WritingToConsole().
WithTextFormat().
Logger()

fmt.Println(slogx.IsInfo(infoLogger))
fmt.Println(slogx.IsInfo(warnLogger))

}

Output

true
false

IsWarn

func IsWarn(logger *slog.Logger) bool

IsWarn checks if the logger is enabled for the warning level.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
warnLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelWarn).
WritingToConsole().
WithTextFormat().
Logger()

errorLogger := slogx.NewBuilder().
WithLevel(slogx.LogLevelError).
WritingToConsole().
WithTextFormat().
Logger()

fmt.Println(slogx.IsWarn(warnLogger))
fmt.Println(slogx.IsWarn(errorLogger))

}

Output

true
false

NewLogger

func NewLogger(opts ...func(options *NewLoggerOptions)) *slog.Logger

NewLogger creates a new slog.Logger with customizable options such as log level, writer, and format.

Example
package main

import (
"github.com/go-softwarelab/common/pkg/slogx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
logger := slogx.NewLogger(skipTimeInLogOutputForExamplePurposes)
logger.Info("test")

}

Output

level=INFO msg=test
Example (With Decorator And Managed Level)

Example using LogLevelManager with NewLogger and WithDecorator. The example sets a level for a pattern before logger creation, logs, then adds another pattern and logs again to show the change.

package main

import (
"log/slog"

"github.com/go-softwarelab/common/pkg/slogx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
// Prepare manager and set a pattern BEFORE creating the logger.
levelManager := slogx.NewLogLevelManager(slogx.LogLevelWarn)
_ = levelManager.SetLevelForServicePattern("OrderService", slog.LevelInfo)

// Build the logger with the manager and a stable text format (without time).
logger := slogx.NewLogger(skipTimeInLogOutputForExamplePurposes, slogx.WithDecorator(levelManager))

// First, create a child logger for the service.
orderSvc := slogx.Child(logger, "OrderService")

// At INFO level for OrderService, debug is filtered, info is printed.
orderSvc.Debug("dbg-1")
orderSvc.Info("info-1")

// Now add a more specific pattern AFTER logger creation.
_ = levelManager.SetLevelForServicePattern("OrderService.Payment", slog.LevelDebug)

// Create a more specific child to include the Payment sub-service.
paymentSvc := slogx.Child(orderSvc, "Payment")

// At DEBUG level for OrderService.Payment, both debug and info are printed.
paymentSvc.Debug("dbg-2")
paymentSvc.Info("info-2")

}

Output

level=INFO msg=info-1 service=OrderService
level=DEBUG msg=dbg-2 service=OrderService service=Payment
level=INFO msg=info-2 service=OrderService service=Payment
Example (With Level)

Example showing how to set a different log level using WithLevel.

package main

import (
"log/slog"

"github.com/go-softwarelab/common/pkg/slogx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
logger := slogx.NewLogger(skipTimeInLogOutputForExamplePurposes, slogx.WithLevel(slog.LevelWarn))

logger.Info("info") // filtered out at WARN level
logger.Warn("warn") // printed

}

Output

level=WARN msg=warn

NewTestLogger

func NewTestLogger(t TestingTBOutput, opts ...func(options *NewLoggerOptions)) *slog.Logger

NewTestLogger creates a new logger instance configured for usage in tests. It writes log output through the provided testing.TB interface with debug level enabled.

Example
package main

import (
"github.com/go-softwarelab/common/pkg/slogx"
"github.com/go-softwarelab/common/pkg/testingx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
// We're simulating a test here in example.
t := &testingx.E{Verbose: true}

logger := slogx.NewTestLogger(t, skipTimeInLogOutputForExamplePurposes)
logger.Info("test")
logger.Debug("test logger is by default at DEBUG level")

}

Output

level=INFO msg=test

level=DEBUG msg="test logger is by default at DEBUG level"
Example (With Level)
package main

import (
"log/slog"

"github.com/go-softwarelab/common/pkg/slogx"
"github.com/go-softwarelab/common/pkg/testingx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
// We're simulating a test here in example.
t := &testingx.E{Verbose: true}

logger := slogx.NewTestLogger(t, skipTimeInLogOutputForExamplePurposes, slogx.WithLevel(slog.LevelInfo))
logger.Info("test")
// This debug message will be filtered out at INFO level.
logger.Debug("test logger is by default at DEBUG level")

}

Output

level=INFO msg=test

Number

func Number[T types.Number](key string, value T) slog.Attr

Number makes easier creation slog.Attr based on any number (int, float, uint) or the custom type over the number type.

Example (Custom Type)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
type MyInt int
type MyFloat float64
type MyUint uint

fmt.Println(slogx.Number("key", MyInt(42)))
fmt.Println(slogx.Number("key", MyFloat(42.5)))
fmt.Println(slogx.Number("key", MyUint(42)))
}

Output

key=42
key=42.5
key=42
Example (Float)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.Number("key", float32(42.5)))
fmt.Println(slogx.Number("key", float64(42.5)))
}

Output

key=42.5
key=42.5
Example (Int)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.Number("key", 42))
fmt.Println(slogx.Number("key", int8(42)))
fmt.Println(slogx.Number("key", int16(42)))
fmt.Println(slogx.Number("key", int32(42)))
fmt.Println(slogx.Number("key", int64(42)))
}

Output

key=42
key=42
key=42
key=42
key=42
Example (Uint)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.Number("key", uint(42)))
fmt.Println(slogx.Number("key", uint8(42)))
fmt.Println(slogx.Number("key", uint16(42)))
fmt.Println(slogx.Number("key", uint32(42)))
fmt.Println(slogx.Number("key", uint64(42)))
}

Output

key=42
key=42
key=42
key=42
key=42

OptionalNumber

func OptionalNumber[T types.Number](key string, value *T) slog.Attr

OptionalNumber makes easier creation slog.Attr based on pointer to any number (int, float, uint) or the custom type over the number type.

Example (Custom Type)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
type MyInt int
n := MyInt(42)
fmt.Println(slogx.OptionalNumber("key", &n))
}

Output

key=42
Example (Float)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
n := 42.5
fmt.Println(slogx.OptionalNumber("key", &n))
}

Output

key=42.5
Example (Int)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
n := 42
fmt.Println(slogx.OptionalNumber("key", &n))
}

Output

key=42
Example (Nil)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
var n *int
fmt.Println(slogx.OptionalNumber("key", n))
}

Output

key=<nil>

OptionalString

func OptionalString[S ~string](key string, value *S) slog.Attr

OptionalString returns a slog.Attr for a string pointer. If the pointer is nil, it sets the value to "<nil>".

Example (Basic)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
s := "value"
fmt.Println(slogx.OptionalString("key", &s))
}

Output

key=value
Example (Custom Type)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
type MyString string
s := MyString("custom value")
fmt.Println(slogx.OptionalString("key", &s))
}

Output

key=custom value
Example (Nil)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
var s *string
fmt.Println(slogx.OptionalString("key", s))
}

Output

key=<nil>

OptionalUserID

func OptionalUserID[ID types.Number | ~string](userID *ID) slog.Attr

OptionalUserID returns a slog.Attr representing the "userId" or a default value of "<unknown>" if userID is nil.

Example (Int)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
id := 42
fmt.Println(slogx.OptionalUserID(&id))
}

Output

userId=42
Example (Nil)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
var id *string
fmt.Println(slogx.OptionalUserID(id))
}

Output

userId=<unknown>
Example (String)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
id := "user123"
fmt.Println(slogx.OptionalUserID(&id))
}

Output

userId=user123

Service

func Service(serviceName string) slog.Attr

Service creates a slog.Attr with the predefined ServiceKey and the given serviceName. This is a conventional attr for marking loggers for services/components in application.

SilentLogger

func SilentLogger() *slog.Logger

SilentLogger returns a new logger instance configured with a handler that discards all log output, effectively creating a logger that won't log any messages.

Example
package main

import (
"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
logger := slogx.SilentLogger()
logger.Info("this message will be discarded")
logger.Error("this error will also be discarded")

}

Output

String

func String[S ~string](key string, value S) slog.Attr

String returns a slog.Attr with the provided key and string value. It's almost the same as a slog.String function, but allows for any custom type based on string to be passed as value.

Example (Basic)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.String("key", "value"))
fmt.Println(slogx.String("empty", ""))
}

Output

key=value
empty=
Example (Custom Type)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
type MyString string
s := MyString("custom value")
fmt.Println(slogx.String("key", s))
}

Output

key=custom value
Example (Empty)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
var s string
fmt.Println(slogx.String("key", s))
}

Output

key=

UserID

func UserID[ID types.Number | ~string](userID ID) slog.Attr

UserID creates a slog.Attr representing the "userId".

Example (Custom Type)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
type UserIDInt int
type UserIDString string

fmt.Println(slogx.UserID(UserIDInt(42)))
fmt.Println(slogx.UserID(UserIDString("user123")))
}

Output

userId=42
userId=user123
Example (Int)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.UserID(42))
}

Output

userId=42
Example (String)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/slogx"
)

func main() {
fmt.Println(slogx.UserID("user123"))
}

Output

userId=user123

WithAdditionalDotPatternAttrKeys

func WithAdditionalDotPatternAttrKeys(keys ...string) func(*DynamicLogLevelOptions)

WithAdditionalDotPatternAttrKeys adds additional keys to the list of keys used for dynamic log level matching. By default, the keys are "service" and "component". The keys are matched against the logger attributes keys and the values are matched against the pattern.

WithDecorator

func WithDecorator(decorator ...HandlerDecorator) func(*NewLoggerOptions)

WithDecorator adds a handler decorator to the logger. The decorator is applied to the handler after it is created. The order of decorators applies from the first to the last.

WithFormat

func WithFormat(format LogFormat) func(*NewLoggerOptions)

WithFormat sets the log format for the logger. To setup logger for tests (NewTestLogger) use WithTestLoggerFormat instead

WithLevel

func WithLevel[L LogLevel | slog.Level](level L) func(*NewLoggerOptions)

WithLevel sets the logging level for the logger. To setup logger for tests (NewTestLogger) use WithTestLoggerLevel instead

WithWriter

func WithWriter(writer io.Writer) func(*NewLoggerOptions)

WithWriter returns a functional option to set a custom io.Writer for logger to output to.

type CollectingLogsWriter

CollectingLogsWriter is a simple io.Writer implementation that writes to a string builder. It is useful for testing purposes - to check what was written by the logger.

type CollectingLogsWriter struct {
strings.Builder
}

NewCollectingLogsWriter

func NewCollectingLogsWriter() *CollectingLogsWriter

NewCollectingLogsWriter creates a new CollectingLogsWriter.

*CollectingLogsWriter.Clear

func (w *CollectingLogsWriter) Clear()

Clear the stored log output.

*CollectingLogsWriter.Lines

func (w *CollectingLogsWriter) Lines() []string

Lines returns a slice of lines from the log output.

type DecoratorOptions

DecoratorOptions is the options for decorating a slog.Handler.

type DecoratorOptions struct {
Additional map[string]any
}

type DynamicLogLevelOptions

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

type HandlerDecorator

HandlerDecorator is an interface for decorating a slog.Handler.

type HandlerDecorator interface {
// DecorateHandler decorates the provided handler and returns the decorated handler.
DecorateHandler(handler slog.Handler, options *DecoratorOptions) slog.Handler
}

type HandlerDecoratorFunc

HandlerDecoratorFunc is a function that implements HandlerDecorator interface.

type HandlerDecoratorFunc func(handler slog.Handler) slog.Handler

HandlerDecoratorFunc.DecorateHandler

func (f HandlerDecoratorFunc) DecorateHandler(handler slog.Handler, _ *DecoratorOptions) slog.Handler

DecorateHandler implements HandlerDecorator interface.

type HandlerDecoratorFuncWithOptions

HandlerDecoratorFuncWithOptions is a function that implements HandlerDecorator interface.

type HandlerDecoratorFuncWithOptions func(handler slog.Handler, options *DecoratorOptions) slog.Handler

HandlerDecoratorFuncWithOptions.DecorateHandler

func (f HandlerDecoratorFuncWithOptions) DecorateHandler(handler slog.Handler, options *DecoratorOptions) slog.Handler

DecorateHandler implements HandlerDecorator interface.

type LogFormat

LogFormat represents different log handler types which can be configured.

type LogFormat string

Supported handler types (based on slog).

const (
// JSONFormat is a standard slog json format.
JSONFormat LogFormat = "json"
// TextFormat is a standard slog text format.
TextFormat LogFormat = "text"
// TextWithoutTimeFormat is a text format without showing the time, it is mostly useful for testing or examples.
TextWithoutTimeFormat LogFormat = "text-no-time"
)

ParseLogFormat

func ParseLogFormat[H ~string](handlerType H) (LogFormat, error)

ParseLogFormat parses a string into a LogFormat enum (case-insensitive).

type LogLevel

LogLevel string representation of different log levels, which can be configured.

type LogLevel string

Supported log levels (based on slog).

const (
LogLevelDebug LogLevel = "debug"
LogLevelInfo LogLevel = "info"
LogLevelWarn LogLevel = "warn"
LogLevelError LogLevel = "error"
LogLevelNone LogLevel = "none"
)

ParseLogLevel

func ParseLogLevel[L ~string](level L) (LogLevel, error)

ParseLogLevel parses a string into a LogLevel enum (case-insensitive).

LogLevel.GetSlogLevel

func (l LogLevel) GetSlogLevel() (slog.Level, error)

GetSlogLevel returns the slog.Level representation of the LogLevel.

LogLevel.MustGetSlogLevel

func (l LogLevel) MustGetSlogLevel() slog.Level

MustGetSlogLevel returns the slog.Level representation of the LogLevel. Panics if the LogLevel is invalid.

type LogLevelManager

LogLevelManager is a logger decorator that allows to configure log levels dynamically based on logger attributes.

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

NewLogLevelManager

func NewLogLevelManager[L slog.Level | LogLevel](level L, opts ...func(*DynamicLogLevelOptions)) *LogLevelManager

NewLogLevelManager creates a new LogLevelManager.

NewLoggerWithManagedLevel

func NewLoggerWithManagedLevel(level LogLevel) (*slog.Logger, *LogLevelManager)

NewLoggerWithManagedLevel creates a new slog.Logger and LogLevelManager with the specified log level. LogLevelManager is applied to the resulting logger. Use the LogLevelManager to change the log level for particular child loggers at runtime.

Example

Example using LogLevelManager obtained from NewLoggerWithManagedLevel. We rebuild a logger with the same manager to control the output format in this example.

package main

import (
"log/slog"

"github.com/go-softwarelab/common/pkg/slogx"
)

var skipTimeInLogOutputForExamplePurposes = slogx.WithFormat(slogx.TextWithoutTimeFormat)

func main() {
// Create a manager via helper and then build a logger with a stable format for the example output.
_, levelManager := slogx.NewLoggerWithManagedLevel(slogx.LogLevelWarn)
logger := slogx.NewLogger(skipTimeInLogOutputForExamplePurposes, slogx.WithDecorator(levelManager))

// Create a service-scoped child logger.
svc := slogx.Child(logger, "OrderService")

// Before adding a pattern, debug is filtered out (default WARN).
svc.Debug("debug before change")

// Enable DEBUG for the specific service using a dot pattern.
_ = levelManager.SetLevelForServicePattern("OrderService", slog.LevelDebug)

// Now DEBUG is enabled for OrderService.
svc.Debug("debug after change")

}

Output

level=DEBUG msg="debug after change" service=OrderService

*LogLevelManager.Decorate

func (m *LogLevelManager) Decorate(handler slog.Handler) slog.Handler

Decorate decorates the given handler with the LogLevelManager.

*LogLevelManager.DecorateHandler

func (m *LogLevelManager) DecorateHandler(handler slog.Handler, _ *DecoratorOptions) slog.Handler

DecorateHandler decorates the given handler with the LogLevelManager.

*LogLevelManager.SetLevel

func (m *LogLevelManager) SetLevel(level slog.Level)

SetLevel sets the default logging level to the specified slog.Level.

*LogLevelManager.SetLevelForServicePattern

func (m *LogLevelManager) SetLevelForServicePattern(pattern string, level slog.Level) error

SetLevelForServicePattern associates a logging level with a given simple dot-separated pattern for dynamic log level matching. Returns an error if the pattern cannot be parsed or the level cannot be set.

Dot-Service-Pattern is a string containing dot-separated services (or components) names, such as "Service.Component". The pattern's dot-separated parts are matched against the logger attributes values whose key is "service" (or "component"). The specified level is applied to all attributes that match the pattern. The most specific matching pattern determines the log level. If multiple patterns of equal specificity match, one is chosen arbitrarily.

For example: Given the patterns: "Service1" and "Service1.Service2", and logger attributes: service="Service1", service="Service2", user=1 the level set for the pattern "Service1.Service2" will be used.

*LogLevelManager.SetLevels

func (m *LogLevelManager) SetLevels(patterns map[string]any) error

SetLevels updates logging levels using a map of patterns and their corresponding levels; returns an error if invalid input. Currently only a dot-service-pattern is supported, see SetLevelForServicePattern for details. Value can be:

  • string - string value parseable to slogx.LogLevel
  • int: any integer value - although it's recommended to use slog.Level values
  • slogx.LogLevel
  • slog.Level

*LogLevelManager.SetLogLevel

func (m *LogLevelManager) SetLogLevel(level LogLevel)

SetLogLevel sets the default logging level to the specified slogx.LogLevel.

type LoggerBuilderWithHandler

type LoggerBuilderWithHandler interface {
// WithHandlerDecorator adds a handler decorator to the logger.
// The decorator is applied to the handler after it is created.
// The order of decorators applies from the first to the last.
WithHandlerDecorator(decorators ...HandlerDecorator) LoggerBuilderWithHandler

LoggerFactory
}

type LoggerFactory

type LoggerFactory interface {
// Logger creates and returns a configured *slog.Logger instance based on the current logger configuration.
Logger() *slog.Logger
}

type LoggerHandlerBuilder

type LoggerHandlerBuilder interface {
// WithTextFormat configures the logger to use a text-based log format.
WithTextFormat() LoggerBuilderWithHandler

// WithJSONFormat configures the logger to use a JSON-based log format.
WithJSONFormat() LoggerBuilderWithHandler

// WithFormat sets the handler of a given type for the logger.
WithFormat(handlerType LogFormat) LoggerBuilderWithHandler
}

type LoggerLevelBuilder

LoggerLevelBuilder is the main interface for configuring a logger.

type LoggerLevelBuilder interface {
// WithLevel sets the log level for the logger.
WithLevel(level LogLevel) LoggerOutputBuilder
// WithSlogLevel sets the log slog.Level for the logger.
WithSlogLevel(level slog.Level) LoggerOutputBuilder
// Silent sets the special logger handler to discard all logs.
Silent() LoggerFactory
}

NewBuilder

func NewBuilder() LoggerLevelBuilder

NewBuilder creates a new Builder for configuring a logger.

type LoggerOpt

LoggerOpt is an alias for functional option for slogx.NewLogger and slogx.NewTestLogger.

type LoggerOpt = func(*NewLoggerOptions)

type LoggerOpts

LoggerOpts is an alias for a slice of functional options for slogx.NewLogger and slogx.NewTestLogger.

type LoggerOpts = []LoggerOpt

type LoggerOutputBuilder

type LoggerOutputBuilder interface {
// WritingToConsole configures a logger to write logs to the stdout
WritingToConsole() LoggerHandlerBuilder

// WritingTo configures the logger to write logs to the provided io.Writer
WritingTo(writer io.Writer) LoggerHandlerBuilder

// WithCustomHandler sets a custom slog.Handler for the logger.
WithCustomHandler(handler slog.Handler) LoggerFactory
}

type NewLoggerOptions

NewLoggerOptions is a set of options for slogx.NewLogger and slogx.NewTestLogger.

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

type RestyLogger

RestyLogger represents an interface of logger required by github.com/go-resty/resty

type RestyLogger interface {
Errorf(format string, v ...interface{})
Warnf(format string, v ...interface{})
Debugf(format string, v ...interface{})
}

RestyAdapter

func RestyAdapter(logger *slog.Logger) RestyLogger

RestyAdapter create an adapter on slog.Logger that will allow it to be use with github.com/go-resty/resty library

type TestingTBOutput

TestingTBOutput is an interface that represents a testing.TB instance required methods to be used by NewTestLogger and TestingTBWriter.

type TestingTBOutput interface {
Helper()
Log(args ...any)
}

type TestingTBWriter

TestingTBWriter is a utility type that implements the io.Writer interface by writing log output to testing.TB. It is commonly used in test scenarios to redirect logs to the test's output via the provided testing.TB instance.

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

NewTestingTBWriter

func NewTestingTBWriter(t TestingTBOutput) *TestingTBWriter

NewTestingTBWriter creates a new TestingTBWriter that writes output to the provided testing.TB instance.

*TestingTBWriter.Write

func (w *TestingTBWriter) Write(p []byte) (n int, err error)

Write writes the provided byte slice to the testing.TB instance.

*TestingTBWriter.WriteString

func (w *TestingTBWriter) WriteString(s string) (n int, err error)

WriteString writes the provided string to the testing.TB instance.