slogutils

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2023 License: MIT Imports: 7 Imported by: 5

README

slogutils

This package provides a middleware and utility functions for slog

GoDoc Go Report Card License

Overview

This package provides middleware and utility functions for easy logging management. It enables color-coded display for different log levels and automatically collects attributes set in the context. This allows developers to have flexible logging recording and analysis capabilities.

Installation

go get github.com/mashiike/slogutils

Usage

package main

import (
	"context"
	"os"
	"log/slog"

	"github.com/fatih/color"
	"github.com/mashiike/slogutils"
)

func main() {
	middleware := slogutils.NewMiddleware(
		slog.NewJSONHandler,
		slogutils.MiddlewareOptions{
			ModifierFuncs: map[slog.Level]slogutils.ModifierFunc{
				slog.LevelDebug: slogutils.Color(color.FgBlack),
				slog.LevelInfo:  nil,
				slog.LevelWarn:  slogutils.Color(color.FgYellow),
				slog.LevelError: slogutils.Color(color.FgRed, color.Bold),
			},
			Writer: os.Stderr,
			HandlerOptions: &slog.HandlerOptions{
				Level: slog.LevelWarn,
			},
		},
	)
	slog.SetDefault(slog.New(middleware))
	ctx := slogutils.With(context.Background(), slog.Int64("request_id", 12))
	slog.WarnContext(ctx, "foo")
	slog.ErrorContext(ctx, "bar")
	slog.DebugContext(ctx, "baz")
	slog.WarnContext(ctx, "buzz")
}

Benchmark

$ go test -bench . -benchmem         
goos: darwin
goarch: arm64
pkg: github.com/mashiike/slogutils
BenchmarkSlogDefault-8                           3304731               343.8 ns/op             0 B/op          0 allocs/op
BenchmarkLogOutput-8                            262371212                4.491 ns/op           0 B/op          0 allocs/op
BenchmarkMiddleware-8                            2929984               415.4 ns/op            48 B/op          1 allocs/op
BenchmarkMiddlewareWithRecordTrnasformer-8       1614752               741.3 ns/op           104 B/op          2 allocs/op
BenchmarkLogOutputWithMiddleware-8              13597328                92.34 ns/op            0 B/op          0 allocs/op
BenchmarkLogOutputWithRecordTransformer-8        1786766               672.7 ns/op             4 B/op          1 allocs/op
PASS
ok      github.com/mashiike/slogutils   10.145s

License

This project is licensed under the MIT License - see the LICENSE(./LICENCE) file for details.

Contribution

Contributions, bug reports, and feature requests are welcome. Pull requests are also highly appreciated. For more details, please

Documentation

Overview

Example
package main

import (
	"context"
	"log"
	"log/slog"
	"os"

	"github.com/fatih/color"
	"github.com/mashiike/slogutils"
)

func main() {
	middleware := slogutils.NewMiddleware(
		slog.NewJSONHandler,
		slogutils.MiddlewareOptions{
			ModifierFuncs: map[slog.Level]slogutils.ModifierFunc{
				slog.LevelDebug: slogutils.Color(color.FgBlack),
				slog.LevelInfo:  nil,
				slog.LevelWarn:  slogutils.Color(color.FgYellow),
				slog.LevelError: slogutils.Color(color.FgRed, color.Bold),
			},
			RecordTransformerFuncs: []slogutils.RecordTransformerFunc{
				slogutils.ConvertLegacyLevel(
					map[string]slog.Level{
						"DEBUG": slog.LevelDebug,
						"INFO":  slog.LevelInfo,
						"WARN":  slog.LevelWarn,
						"ERROR": slog.LevelError,
					},
					false,
				),
			},
			Writer: os.Stdout,
			HandlerOptions: &slog.HandlerOptions{
				Level: slog.LevelWarn,
				ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
					if a.Key == "time" {
						return slog.Attr{}
					}
					return a
				},
			},
		},
	)
	slog.SetDefault(slog.New(middleware))
	ctx := slogutils.With(context.Background(), slog.Int64("request_id", 12))
	slog.WarnContext(ctx, "foo")
	slog.ErrorContext(ctx, "bar")
	slog.DebugContext(ctx, "baz")
	slog.WarnContext(ctx, "buzz")
	log.Println("[DEBUG] this is not slog.")
	log.Println("[INFO] this is not slog.")
	log.Println("[WARN] this is not slog.")
	log.Println("[ERROR] this is not slog.")

}
Output:

{"level":"WARN","msg":"foo","request_id":12}
{"level":"ERROR","msg":"bar","request_id":12}
{"level":"WARN","msg":"buzz","request_id":12}
{"level":"WARN","msg":"this is not slog."}
{"level":"ERROR","msg":"this is not slog."}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertLegacyLevel added in v0.2.0

func ConvertLegacyLevel(levelMap map[string]slog.Level, caseInsensitive bool) func(slog.Record) slog.Record

ConvertLegacyLevel returns a RecordTransformerFunc that converts legacy level to slog.Level. The legacy level is the first word in the message enclosed in square brackets. The levelMap maps the legacy level to slog.Level. If caseInsensitive is true, the legacy level is case insensitive. If the legacy level is not found in the levelMap, the slog.Record is not changed. If the slog.Record.Level is not slog.LevelInfo, the slog.Record is not changed.

Example:

ConvertLegacyLevel(map[string]slog.Level{"debug": slog.LevelDebug}, true)
If the message is "[DEBUG] hello world", the slog.Record.Level is converted to slog.LevelDebug.

func DefaultAttrs

func DefaultAttrs(args ...any) func(slog.Record) slog.Record

DefaultAttrs returns a RecordTransformerFunc that adds the given attributes to a slog.Record if they don't already exist.

func DropAttrs

func DropAttrs(keys ...string) func(slog.Record) slog.Record

DropAttrs returns a RecordTransformerFunc that drops the given attributes from a slog.Record.

func RenameAttrs added in v0.2.0

func RenameAttrs(m map[string]string) func(slog.Record) slog.Record

RenameAttrs returns a RecordTransformerFunc that renames the given attributes from a slog.Record.

func UniqueAttrs added in v0.2.0

func UniqueAttrs() func(slog.Record) slog.Record

UniqueAttrs returns a RecordTransformerFunc that removes duplicate attributes from a slog.Record.

func With

func With(ctx context.Context, args ...any) context.Context

Types

type Middleware

type Middleware[H slog.Handler] struct {
	// contains filtered or unexported fields
}

Middleware is a slog.Handler that modifies log lines.

func NewMiddleware

func NewMiddleware[H slog.Handler](f func(io.Writer, *slog.HandlerOptions) H, opts MiddlewareOptions) *Middleware[H]

func (*Middleware[H]) Clone

func (m *Middleware[H]) Clone() *Middleware[H]

Clone returns a new Middleware with the same Handler and modifierFuncs.

func (*Middleware[H]) Enabled

func (m *Middleware[H]) Enabled(ctx context.Context, l slog.Level) bool

func (*Middleware[H]) Handle

func (m *Middleware[H]) Handle(ctx context.Context, record slog.Record) error

Handle implements slog.Handler.

func (*Middleware[H]) SetMinLevel added in v0.4.0

func (m *Middleware[H]) SetMinLevel(l slog.Leveler)

func (*Middleware[H]) WithAttrs

func (m *Middleware[H]) WithAttrs(as []slog.Attr) slog.Handler

func (*Middleware[H]) WithGroup

func (m *Middleware[H]) WithGroup(name string) slog.Handler

type MiddlewareOptions

type MiddlewareOptions struct {
	// ModifierFuncs is a map of log levels to ModifierFunc.
	ModifierFuncs map[slog.Level]ModifierFunc

	// RecordTransformerFuncs is a list of RecordTransformerFunc.
	RecordTransformerFuncs []RecordTransformerFunc

	// Writer is the writer to write to.
	Writer io.Writer

	// HandlerOptions are options for the handler.
	HandlerOptions *slog.HandlerOptions
}

MiddlewareOptions are options for creating a Middleware.

type ModifierFunc

type ModifierFunc func([]byte) []byte

ModifierFunc is a function that modifies a log line.

func Color

func Color(attr ...color.Attribute) ModifierFunc

Color returns a ModifierFunc that colors the log line.

type RecordTransformerFunc

type RecordTransformerFunc func(slog.Record) slog.Record

RecordTransformerFunc is a function that transforms a slog.Record.

Jump to

Keyboard shortcuts

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