logger

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2024 License: MIT Imports: 20 Imported by: 10

Documentation

Overview

Package logger implements a simple logger based on log/slog.

NanoHandler formats slog.Record as a sequence of value strings without attribute keys to minimize log length.

2023/08/16 00:35:15 [I] Service httpd started: <http://127.0.0.1:9000>
2023/08/16 00:35:15 [D] Use default cache dir: /root/.cache/glb
2023/08/16 00:35:15 [W] Failed to check for updates: i/o timeout
2023/08/16 00:35:15 [E] dial tcp 127.0.0.1:9000: connect: connection refused
2023/08/16 00:35:15 [F] mkdir /root/.config/glb: permission denied

2023/08/16 00:35:15 [I] REQ_BEG 10.0.3.201 GET /status R5U3KA5C-42
2023/08/16 00:35:15 [I] TX_SVC1 Fetch upstream metrics http://127.0.0.1:8080/metrics 3 R5U3KA5C-42
2023/08/16 00:35:15 [I] REQ_END 200 4 10.0.3.201 GET /status R5U3KA5C-42

TextHandler formats slog.Record as a sequence of key=value pairs separated by spaces and followed by a newline.

time=2023-08-16T00:35:15+08:00 level=INFO msg="Service httpd started: <http://127.0.0.1:9000>"
time=2023-08-16T00:35:15+08:00 level=DEBUG msg="Use default cache dir: /root/.cache/glb"
time=2023-08-16T00:35:15+08:00 level=WARN msg="Failed to check for updates: i/o timeout"
time=2023-08-16T00:35:15+08:00 level=ERROR msg="dial tcp 127.0.0.1:9000: connect: connection refused"
time=2023-08-16T00:35:15+08:00 level=FATAL msg="mkdir /root/.config/glb: permission denied"

time=2023-08-16T00:35:15+08:00 level=INFO msg="" tag=REQ_BEG ip=10.0.3.201 method=GET path=/status tid=R5U3KA5C-42
time=2023-08-16T00:35:15+08:00 level=INFO msg="Fetch upstream metrics" tag=TX_SVC1 url=http://127.0.0.1:8080/metrics duration=3 tid=R5U3KA5C-42
time=2023-08-16T00:35:15+08:00 level=INFO msg="" tag=REQ_END code=200 duration=4 ip=10.0.3.201 method=GET path=/status tid=R5U3KA5C-42

JsonHandler formats slog.Record as line-delimited JSON objects.

{"time":"2023-08-16T00:35:15.208873091+08:00","level":"INFO","msg":"Service httpd started: <http://127.0.0.1:9000>"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"DEBUG","msg":"Use default cache dir: /root/.cache/glb"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"WARN","msg":"Failed to check for updates: i/o timeout"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"ERROR","msg":"dial tcp 127.0.0.1:9000: connect: connection refused"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"FATAL","msg":"mkdir /root/.config/glb: permission denied"}

{"time":"2023-08-16T00:35:15.208873091+08:00","level":"INFO","msg":"","tag":"REQ_BEG","ip":"10.0.3.201","method":"GET","path":"/status","tid":"R5U3KA5C-42"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"INFO","msg":"Fetch upstream metrics","tag":"TX_SVC1","url":"http://127.0.0.1:8080/metrics","duration":3,"tid":"R5U3KA5C-42"}
{"time":"2023-08-16T00:35:15.208873091+08:00","level":"INFO","msg":"","tag":"REQ_END","code":200,"duration":4,"ip":"10.0.3.201","method":"GET","path":"/status","tid":"R5U3KA5C-42"}

Index

Constants

View Source
const (
	LevelDebug slog.Level = 0  // For debugging in dev environment
	LevelInfo  slog.Level = 4  // For parameters, requests, responses and metrics
	LevelWarn  slog.Level = 8  // For issues that do not affect workflow
	LevelError slog.Level = 12 // For issues that do affect workflow
	LevelFatal slog.Level = 16 // For issues that require immediate termination
)

logger's valid levels

Variables

This section is empty.

Functions

func ValidLevel added in v1.3.0

func ValidLevel(l slog.Level) bool

ValidLevel reports whether the given level is one of logger's valid levels.

Types

type AnsiString added in v1.3.0

type AnsiString struct {
	Prefix string
	Value  string
}

type Handler added in v1.3.0

type Handler interface {
	Enabled(slog.Level) bool
	IsDebug() bool
	IsColorful() bool
	IsAddSource() bool

	WithAttrs(attrs []slog.Attr) Handler
	WithGroup(name string) Handler
	Handle(context.Context, slog.Record) error
}

Handler handles log records produced by a Logger.

Users should use the methods of Logger instead of invoking Handler methods directly.

type JsonHandler added in v1.3.0

type JsonHandler struct {
	*Options
	// contains filtered or unexported fields
}

JsonHandler formats slog.Record as line-delimited JSON objects.

func NewJsonHandler added in v1.3.0

func NewJsonHandler(w io.Writer, opts *Options) *JsonHandler

NewJsonHandler creates a new JsonHandler with the given io.Writer and Options. The Options should not be changed after first use.

func (*JsonHandler) Handle added in v1.3.0

func (h *JsonHandler) Handle(_ context.Context, r slog.Record) error

Handle formats slog.Record as a JSON object on a single line.

The time is output in time.RFC3339Nano format.

An encoding failure does not cause Handle to return an error. Instead, the error message is formatted as a string.

func (*JsonHandler) WithAttrs added in v1.3.0

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

WithAttrs returns a new JsonHandler whose attributes consists of h's attributes followed by attrs. If attrs is empty, WithAttrs returns the origin JsonHandler.

func (*JsonHandler) WithGroup added in v1.3.0

func (h *JsonHandler) WithGroup(name string) Handler

WithGroup returns a new JsonHandler that starts a group with the given name. If name is empty, WithGroup returns the origin JsonHandler.

type Logger added in v1.3.0

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

Logger provides output methods for creating a slog.Record and passing it to the internal Handler.

func New added in v1.3.0

func New(h Handler) *Logger

New creates a new Logger with the given Handler.

func (*Logger) Debug added in v1.3.0

func (l *Logger) Debug(msg string, args ...any)

Debug logs at LevelDebug.

If args need heavy computation, should wrap them with a conditional block or use the LogValuer interface to defer expensive operations. Example:

if logger.IsDebug() {
    diffs := calcDifference(A, B)
    logger.Debug("compare A to B: " + diffs)
}

func (*Logger) Debugf added in v1.3.3

func (l *Logger) Debugf(format string, args ...any)

Debugf formats message at LevelDebug.

func (*Logger) Error added in v1.3.0

func (l *Logger) Error(msg string, args ...any)

Error logs at LevelError.

func (*Logger) Errorf added in v1.3.3

func (l *Logger) Errorf(format string, args ...any)

Errorf formats message at LevelError.

func (*Logger) Fatal added in v1.3.0

func (l *Logger) Fatal(msg string, args ...any)

Fatal logs at LevelFatal and follows with a call to os.Exit(1).

func (*Logger) Fatalf added in v1.3.3

func (l *Logger) Fatalf(format string, args ...any)

Fatalf formats message at LevelFatal and follows with a call to os.Exit(1).

func (*Logger) Info added in v1.3.0

func (l *Logger) Info(msg string, args ...any)

Info logs at LevelInfo.

func (*Logger) Infof added in v1.3.3

func (l *Logger) Infof(format string, args ...any)

Infof formats message at LevelInfo.

func (*Logger) Log added in v1.3.0

func (l *Logger) Log(ctx context.Context, level slog.Level, msg string, args ...any)

Log emits a log record with the current time and the given level and message.

func (*Logger) LogAttrs added in v1.3.0

func (l *Logger) LogAttrs(ctx context.Context, level slog.Level, msg string, attrs ...slog.Attr)

LogAttrs is a more efficient version of Logger.Log that accepts only Attrs.

func (*Logger) Logf added in v1.3.3

func (l *Logger) Logf(ctx context.Context, level slog.Level, format string, args ...any)

Logf emits a log record with the current time and the given level and format message.

func (*Logger) Panic added in v1.3.0

func (l *Logger) Panic(msg string, args ...any)

Panic logs at LevelError and follows with a call to panic(msg).

func (*Logger) Panicf added in v1.3.3

func (l *Logger) Panicf(format string, args ...any)

Panicf formats message at LevelError and follows with a call to panic(message).

func (*Logger) Relay added in v1.3.0

func (l *Logger) Relay(store *httpd.Store)

func (*Logger) Warn added in v1.3.0

func (l *Logger) Warn(msg string, args ...any)

Warn logs at LevelWarn.

func (*Logger) Warnf added in v1.3.3

func (l *Logger) Warnf(format string, args ...any)

Warnf formats message at LevelWarn.

func (*Logger) With added in v1.3.0

func (l *Logger) With(args ...any) *Logger

With returns a Logger that includes the given args in each output operation. If args is empty, With returns the origin Logger.

func (*Logger) WithGroup added in v1.3.0

func (l *Logger) WithGroup(name string) *Logger

WithGroup returns a Logger that starts a group with the given name. If name is empty, WithGroup returns the origin Logger.

type NanoHandler added in v1.3.0

type NanoHandler struct {
	*Options
	// contains filtered or unexported fields
}

NanoHandler formats slog.Record as a sequence of value strings without attribute keys to minimize log length.

func NewNanoHandler added in v1.3.0

func NewNanoHandler(w io.Writer, opts *Options) *NanoHandler

NewNanoHandler creates a new NanoHandler with the given io.Writer and Options. The Options should not be changed after first use.

func (*NanoHandler) Handle added in v1.3.0

func (h *NanoHandler) Handle(_ context.Context, r slog.Record) error

Handle formats slog.Record as a sequence of value strings without attribute keys.

The time is output in time.DateTime format.

If the Record's message is empty, the message is omitted.

func (*NanoHandler) WithAttrs added in v1.3.0

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

WithAttrs returns a new NanoHandler whose attributes consists of h's attributes followed by attrs. If attrs is empty, WithAttrs returns the origin NanoHandler.

func (*NanoHandler) WithGroup added in v1.3.0

func (h *NanoHandler) WithGroup(name string) Handler

WithGroup returns the origin NanoHandler because NanoHandler always ignores attribute keys.

type Options added in v1.3.0

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

Options is the common options for all handlers.

func NewOptions added in v1.3.0

func NewOptions(level slog.Level, colorful bool, addSource bool) *Options

NewOptions creates a new Options with the given level, colorful and addSource.

func (*Options) Enabled added in v1.3.0

func (opts *Options) Enabled(l slog.Level) bool

Enabled reports whether the given level is enabled.

func (*Options) IsAddSource added in v1.3.0

func (opts *Options) IsAddSource() bool

IsAddSource reports whether the handler adds source info.

func (*Options) IsColorful added in v1.3.0

func (opts *Options) IsColorful() bool

IsColorful reports whether the handler enables colorful level labels.

func (*Options) IsDebug added in v1.3.0

func (opts *Options) IsDebug() bool

IsDebug reports whether the handler is LevelDebug.

type TextHandler added in v1.3.0

type TextHandler struct {
	*Options
	// contains filtered or unexported fields
}

TextHandler formats slog.Record as a sequence of key=value pairs separated by spaces and followed by a newline.

func NewTextHandler added in v1.3.0

func NewTextHandler(w io.Writer, opts *Options) *TextHandler

NewTextHandler creates a new TextHandler with the given io.Writer and Options. The Options should not be changed after first use.

func (*TextHandler) Handle added in v1.3.0

func (h *TextHandler) Handle(_ context.Context, r slog.Record) error

Handle formats slog.Record as a single line of space-separated key=value items.

The time is output in time.RFC3339 format.

Keys and values are quoted with strconv.Quote if they contain Unicode space characters, non-printing characters, '"' or '='.

func (*TextHandler) WithAttrs added in v1.3.0

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

WithAttrs returns a new TextHandler whose attributes consists of h's attributes followed by attrs. If attrs is empty, WithAttrs returns the origin TextHandler.

func (*TextHandler) WithGroup added in v1.3.0

func (h *TextHandler) WithGroup(name string) Handler

WithGroup returns a new TextHandler that starts a group with the given name. If name is empty, WithGroup returns the origin TextHandler.

Jump to

Keyboard shortcuts

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