slogtool

package module
v0.0.0-...-2b12c23 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 15 Imported by: 0

README

go-slogtool

CI GoDoc GitHub issues GitHub forks GitHub stars GitHub license

log/slog wrappers and tools.

Install

go get -u github.com/na4ma4/go-slogtool

Tools

LogLevels
ctx := context.Background()
logmgr := slogtool.NewSlogManager(
    ctx,
    slogtool.WithDefaultLevel(slog.LevelDebug),
)

processOne := server.NewProcess(logmgr.Named("Server.Process"))

// somewhere else.

logmgr.SetLevel("Server.Process", "debug")

// and triggered somewhere else again.

logmgr.SetLevel("Server.Process", "info")
HTTP Logging Handler
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("This is a catch-all route"))
})

loggedRouter := slogtool.LoggingHTTPHandler(logmgr.Named("WebServer"), r)
http.ListenAndServe(":1123", loggedRouter)

Documentation

Index

Constants

View Source
const (
	HeaderUsername = "X-Logging-Username"
	HeaderNoop     = "X-Logging-Noop"
)

Variables

View Source
var ErrUnimplemented = errors.New("unimplemented method")

ErrUnimplemented is returned when a method is unimplemented.

Functions

func ErrorAttr

func ErrorAttr(err error) slog.Attr

func ErrorLevel

func ErrorLevel(err error) slog.Level

func LoggingHTTPHandler

func LoggingHTTPHandler(logger *slog.Logger, httpHandler http.Handler, opts ...loggingOptionsFunc) http.Handler

LoggingHTTPHandler return a http.Handler that wraps h and logs requests to out using a *slog.Logger.

func LoggingHTTPHandlerWrapper

func LoggingHTTPHandlerWrapper(logger *slog.Logger, opts ...loggingOptionsFunc) func(next http.Handler) http.Handler

func LoggingOptionForwardedFor

func LoggingOptionForwardedFor(state bool) loggingOptionsFunc

LoggingOptionForwardedFor defines if the logging should contain a `http.forwarded_for` field.

func LoggingOptionLogLevel

func LoggingOptionLogLevel(level slog.Leveler) loggingOptionsFunc

LoggingOptionLogLevel defines the log level that http messages should output to, defaults to Info.

func LoggingOptionTimestamp

func LoggingOptionTimestamp(state bool) loggingOptionsFunc

LoggingOptionTimestamp defines if the logging should contain a `http.timestamp` field.

func LoggingOptionTiming

func LoggingOptionTiming(state bool) loggingOptionsFunc

LoggingOptionTiming defines if the logging should contain a `http.request_time` field.

func Stack

func Stack(name string) slog.Attr

func TestLogger

func TestLogger(w io.Writer) (*slog.LevelVar, *slog.Logger)

func TestLoggerOnly

func TestLoggerOnly(w io.Writer) *slog.Logger

Types

type CustomNewHandler

type CustomNewHandler func(name string, w io.Writer, opts *slog.HandlerOptions) slog.Handler

type LogManager

type LogManager interface {
	NewLevel(name string) slog.Leveler
	Named(name string, opts ...interface{}) *slog.Logger
	Iterator(f func(name string, level slog.Leveler) error) error
	IsLogger(name string) bool
	SetLevel(name string, lvl interface{}) bool
	Delete(name string)
	String() string
}

type SlogHandlerWrapper

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

func NewSlogHandlerWrapper

func NewSlogHandlerWrapper(handler slog.Handler, lvl slog.Leveler) *SlogHandlerWrapper

func (*SlogHandlerWrapper) Enabled

func (h *SlogHandlerWrapper) Enabled(_ context.Context, in slog.Level) bool

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower. It is called early, before any arguments are processed, to save effort if the log event should be discarded. If called from a Logger method, the first argument is the context passed to that method, or context.Background() if nil was passed or the method does not take a context. The context is passed so Enabled can use its values to make a decision.

func (*SlogHandlerWrapper) Handle

func (h *SlogHandlerWrapper) Handle(ctx context.Context, r slog.Record) error

Handle handles the Record. It will only be called when Enabled returns true. The Context argument is as for Enabled. It is present solely to provide Handlers access to the context's values. Canceling the context should not affect record processing. (Among other things, log messages may be necessary to debug a cancellation-related problem.)

Handle methods that produce output should observe the following rules:

  • If r.Time is the zero time, ignore the time.
  • If r.PC is zero, ignore it.
  • Attr's values should be resolved.
  • If an Attr's key and value are both the zero value, ignore the Attr. This can be tested with attr.Equal(Attr{}).
  • If a group's key is empty, inline the group's Attrs.
  • If a group has no Attrs (even if it has a non-empty key), ignore it.

func (*SlogHandlerWrapper) SetLevel

func (h *SlogHandlerWrapper) SetLevel(lvl slog.Level)

Level return a reference to *slog.LevelVar so the level can be changed on request.

func (*SlogHandlerWrapper) WithAttrs

func (h *SlogHandlerWrapper) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments. The Handler owns the slice: it may retain, modify or discard it.

func (*SlogHandlerWrapper) WithGroup

func (h *SlogHandlerWrapper) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups. The keys of all subsequent attributes, whether added by With or in a Record, should be qualified by the sequence of group names.

How this qualification happens is up to the Handler, so long as this Handler's attribute keys differ from those of another Handler with a different sequence of group names.

A Handler should treat WithGroup as starting a Group of Attrs that ends at the end of the log event. That is,

logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2))

should behave like

logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))

If the name is empty, WithGroup returns the receiver.

type SlogManager

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

SlogManager provides a wrapper for multiple *slog.Logger levels, the individual loggers are not kept, but levels are kept indexed by name.

func NewSlogManager

func NewSlogManager(opts ...interface{}) *SlogManager

NewSlogManager returns a new SlogManager ready for use.

func (*SlogManager) Delete

func (a *SlogManager) Delete(name string)

Delete removes the named logger entry from the list.

func (*SlogManager) IsLogger

func (a *SlogManager) IsLogger(name string) bool

IsLogger returns true if there is a logger that matches.

func (*SlogManager) Iterator

func (a *SlogManager) Iterator(f func(string, slog.Leveler) error) error

Iterator runs a callback function over the levels map item by item.

func (*SlogManager) Named

func (a *SlogManager) Named(name string, opts ...interface{}) *slog.Logger

Named returns a named *slog.Logger if any additional parameters are specified it will try to determine if they represent a log level (by string, zapcore.Level or slog.Leveler).

func (*SlogManager) NewLevel

func (a *SlogManager) NewLevel(name string) slog.Leveler

NewLevel returns as a log.Leveler reference to the stored named level.

func (*SlogManager) SetLevel

func (a *SlogManager) SetLevel(name string, lvl interface{}) bool

SetLevel attempts to set the level supplied, it will attempt to typecast the value against string, slog.Level and slog.Leveler.

func (*SlogManager) String

func (a *SlogManager) String() string

String returns a string representation of the currently stored loggers and their levels.

type SlogManagerHandlerOpts

type SlogManagerHandlerOpts func(*slog.HandlerOptions)

func WithLevel

func WithLevel(lvl interface{}) SlogManagerHandlerOpts

func WithSource

func WithSource(withSource bool) SlogManagerHandlerOpts

type SlogManagerOpts

type SlogManagerOpts func(*SlogManager)

func WithCustomHandler

func WithCustomHandler(custom CustomNewHandler) SlogManagerOpts

func WithDefaultLevel

func WithDefaultLevel(lvl interface{}) SlogManagerOpts

func WithInternalLevel

func WithInternalLevel(lvl interface{}) SlogManagerOpts

func WithJSONHandler

func WithJSONHandler() SlogManagerOpts

func WithTextHandler

func WithTextHandler() SlogManagerOpts

func WithWriter

func WithWriter(out io.Writer) SlogManagerOpts

type SlogNullHandler

type SlogNullHandler struct{}

func (SlogNullHandler) Enabled

func (SlogNullHandler) Enabled(_ context.Context, _ slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (SlogNullHandler) Handle

Handle handles the Record.

func (SlogNullHandler) WithAttrs

func (SlogNullHandler) WithAttrs(_ []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments. The Handler owns the slice: it may retain, modify or discard it.

func (SlogNullHandler) WithGroup

func (SlogNullHandler) WithGroup(_ string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

Jump to

Keyboard shortcuts

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