Documentation
¶
Overview ¶
The slog package provides utilities for log/slog use cases.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( // ErrUnknownHandlerName is returned when an unknown slog handler name is used. ErrUnknownHandlerName = errors.New("unknown handler name") )
Errors used by the slog package.
Functions ¶
func NewSlogLogger ¶
NewSlogLogger creates an slog Logger that outputs to writer, using the specified log handler and the specified leveler implementation (for minimum logging level). This function also renames the built-in slog.TimeKey attribute to "ts" for shorter log lines.
Example ¶
package main import ( "log/slog" "os" tkslog "github.com/hhromic/go-toolkit/slog" ) func main() { h := tkslog.HandlerText l := slog.LevelDebug logger := tkslog.NewSlogLogger(os.Stdout, h, l) version := "1.2.3" logger.Info("application started", "version", version) }
Output:
Example (SetDefault) ¶
package main import ( "log/slog" "os" tkslog "github.com/hhromic/go-toolkit/slog" ) func main() { h := tkslog.HandlerText l := slog.LevelDebug logger := tkslog.NewSlogLogger(os.Stdout, h, l) slog.SetDefault(logger) version := "1.2.3" slog.Info("application started", "version", version) }
Output:
Types ¶
type Handler ¶
type Handler int
Handler represents a supported slog handler.
const ( // HandlerText is an slog TextHandler which outputs logs in key=value format. HandlerText Handler = iota // HandlerJSON is an slog JSONHandler which outputs logs in standard JSON format. HandlerJSON // HandlerTint is an slog Handler which outputs colorized logs in key=value format. HandlerTint // HandlerAuto uses HandlerTint if the output writer is a terminal or HandlerText otherwise. HandlerAuto )
Supported slog handlers.
func (Handler) MarshalText ¶
MarshalText implements encoding.TextMarshaler by calling Handler.String.
Example ¶
package main import ( "fmt" tkslog "github.com/hhromic/go-toolkit/slog" ) func main() { h := tkslog.HandlerText b, err := h.MarshalText() if err != nil { panic(err) } fmt.Println(b) }
Output: [116 101 120 116]
func (Handler) String ¶
String returns a name for the slog handler.
Example ¶
package main import ( "fmt" tkslog "github.com/hhromic/go-toolkit/slog" ) func main() { h := tkslog.HandlerText fmt.Println(h.String()) }
Output: text
func (*Handler) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler. It accepts any slice of bytes produced by Handler.MarshalText.
Example ¶
package main import ( "fmt" tkslog "github.com/hhromic/go-toolkit/slog" ) func main() { b := []byte{116, 101, 120, 116} var h tkslog.Handler if err := h.UnmarshalText(b); err != nil { panic(err) } fmt.Println(h.String()) }
Output: text
Click to show internal directories.
Click to hide internal directories.