pretty

package
v0.0.0-...-039c39c Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 11 Imported by: 0

README

hypera.dev/lib/slog/pretty

Go Reference

A human-readable and optionally coloured slog.Handler.

The output format is designed to be quick and easy to read, primarily for use in development environments. This format is not necessarily recommended for production environments, especially where logs need to be parsed to extract data.

Example image

go get -u hypera.dev/lib/slog/pretty

Usage

// Create a new logger
log := slog.New(pretty.NewHandler(os.Stdout, nil))

// Set global logger and use custom options
slog.SetDefault(slog.New(
	pretty.NewHandler(os.Stdout, &pretty.Options{
		Level:         slog.LevelDebug,
		AddSource:     true,
	}),
))

Customisable

It is possible to customise how certain parts of the output are formatted by passing different formatters in pretty.Options. It is not currently possible to reorder parts of the output, however this feature may be added in the future.

Time formatter
// Change the time format using the default formatter
pretty.NewHandler(w, &pretty.Options{
	TimeFormatter: pretty.DefaultTimeFormatter(time.DateTime),
}),

// Use a custom time formatter
pretty.NewHandler(w, &pretty.Options{
	TimeFormatter: func(buf *pretty.Buffer, t time.Time) {
		buf.AppendTimeFormat(t, time.DateTime)
	},
}),
Level formatter
// Use the default level formatter
pretty.NewHandler(w, &pretty.Options{
	LevelFormatter: pretty.DefaultLevelFormatter(color),
}),

// Use a custom level formatter
pretty.NewHandler(w, &pretty.Options{
	LevelFormatter: func(buf *pretty.Buffer, l slog.Level) {
		if l == LevelTrace {
			buf.AppendString("TRACE")
			return
		}
		pretty.DefaultLevelFormatter(true),
	},
}),
Source formatter
// Use the default source formatter
pretty.NewHandler(w, &pretty.Options{
	LevelFormatter: pretty.DefaultSourceFormatter(color),
}),

// Use a custom source formatter
pretty.NewHandler(w, &pretty.Options{
	SourceFormatter: func(buf *pretty.Buffer, src *slog.Source) {
		dir, file := filepath.Split(src.File)

		buf.AppendByte('<')
		buf.AppendString(filepath.Join(filepath.Base(dir), file))
		buf.AppendByte(':')
		buf.AppendInt(int64(src.Line))
		buf.AppendByte('>')
	},
}),

Extras

Automatic color toggle

Colored output is enabled by default and can be disabled by setting DisableColor: false in the handler options. You can have colors automatically enabled depending on the terminal capabilities with the use of a package like github.com/mattn/go-isatty.

w := os.Stdout
pretty.NewHandler(w, &pretty.Options{
	DisableColor: !isatty.IsTerminal(w.Fd()),
}),
Windows support

Colors may display weirdly on Windows, and can be corrected with use of the github.com/mattn/go-colorable package.

w := os.Stdout
pretty.NewHandler(colorable.NewColorable(w), nil)

Acknowledgements

The output format is heavily inspired by github.com/charmbracelet/log and github.com/lmittmann/tint.

github.com/lmittmann/tint is a great alternative to this library, however it does not currently support custom time, level or source formatters.

Documentation

Overview

Package pretty implements a slog.Handler that writes human-readable and optionally coloured logs.

The output format can be customised with Options.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHandler

func NewHandler(w io.Writer, opts *Options) slog.Handler

NewHandler returns a slog.Handler that writes human-readable and optionally coloured logs to the writer.

Types

type Buffer

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

Buffer is a simple wrapper around a byte slice.

func (*Buffer) AppendBool

func (b *Buffer) AppendBool(v bool)

AppendBool writes "true" or "false" to the buffer according to the given bool.

func (*Buffer) AppendByte

func (b *Buffer) AppendByte(p byte)

AppendByte writes the given byte to the buffer.

func (*Buffer) AppendBytes

func (b *Buffer) AppendBytes(p []byte)

AppendBytes writes the given byte slice to the buffer.

func (*Buffer) AppendFloat

func (b *Buffer) AppendFloat(f float64, bitSize int)

AppendFloat writes the given float to the buffer with the given bitSize.

func (*Buffer) AppendFloat32

func (b *Buffer) AppendFloat32(f float32)

AppendFloat32 writes the given float32 to the buffer.

func (*Buffer) AppendFloat64

func (b *Buffer) AppendFloat64(f float64)

AppendFloat64 writes the given float64 to the buffer.

func (*Buffer) AppendInt

func (b *Buffer) AppendInt(i int64)

AppendInt writes the given int64 to the buffer.

func (*Buffer) AppendQuote

func (b *Buffer) AppendQuote(s string)

AppendQuote writes a double-quoted string to the buffer using the strconv.AppendQuote function.

func (*Buffer) AppendString

func (b *Buffer) AppendString(s string)

AppendString writes the given string to the buffer.

func (*Buffer) AppendTimeFormat

func (b *Buffer) AppendTimeFormat(t time.Time, layout string)

AppendTimeFormat writes a timestamp to the buffer in the given format.

func (*Buffer) AppendUint

func (b *Buffer) AppendUint(i uint64)

AppendUint writes the given uint64 to the buffer.

func (*Buffer) Cap

func (b *Buffer) Cap() int

Cap returns the capacity of the underlying byte slice.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the length of the underlying byte slice.

func (*Buffer) Replace

func (b *Buffer) Replace(i int, p byte)

Replace replaces the byte at index i with the given byte, if the underlying byte slice contains index i.

func (*Buffer) Reset

func (b *Buffer) Reset()

Reset resets the underlying byte slice.

func (*Buffer) String

func (b *Buffer) String() string

String returns a string copy of the underlying byte slice.

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (int, error)

Write writes the given bytes to the buffer.

func (*Buffer) WriteString

func (b *Buffer) WriteString(s string) (int, error)

WriteString writes the given string to the buffer.

func (*Buffer) WriteTo

func (b *Buffer) WriteTo(writer io.Writer) (int64, error)

WriteTo writes the buffer contents to the given writer.

type LevelFormatter

type LevelFormatter func(buf *Buffer, l slog.Level)

LevelFormatter writes the formatted level to the buffer.

func DefaultLevelFormatter

func DefaultLevelFormatter(color bool) LevelFormatter

DefaultLevelFormatter is the default LevelFormatter.

type Options

type Options struct {
	// Level is the minimum [slog.Level] that will be logged.
	// Records with lower levels will be discarded.
	Level slog.Leveler

	// ReplaceAttr is used to rewrite each non-group [slog.Attr] before it is
	// logged. See https://pkg.go.dev/log/slog#HandlerOptions for details.
	ReplaceAttr ReplaceAttrFunc

	// AddSource enables computing the source code position of the log
	// statement and adds [slog.SourceKey] attributes to the output.
	AddSource bool

	// DisableColor disables the use of ANSI colour codes in messages.
	DisableColor bool

	// TimeFormatter is the [time.Time] formatter used to format log timestamps.
	TimeFormatter TimeFormatter

	// LevelFormatter is the [slog.Level] formatter used to format log levels.
	LevelFormatter LevelFormatter

	// SourceFormatter is the [slog.Source] formatter used to format log sources.
	SourceFormatter SourceFormatter
}

Options allows you to customise the output format. This is a drop-in replacement for slog.HandlerOptions.

type ReplaceAttrFunc

type ReplaceAttrFunc func(groups []string, attr slog.Attr) slog.Attr

ReplaceAttrFunc is used to rewrite each non-group slog.Attr before it is logged.

type SourceFormatter

type SourceFormatter func(buf *Buffer, src *slog.Source)

SourceFormatter writes the formatted log source to the buffer.

func DefaultSourceFormatter

func DefaultSourceFormatter(color bool) SourceFormatter

DefaultSourceFormatter is the default SourceFormatter.

type TimeFormatter

type TimeFormatter func(buf *Buffer, t time.Time)

TimeFormatter writes the formatted time to the buffer.

func DefaultTimeFormatter

func DefaultTimeFormatter(layout string) TimeFormatter

DefaultTimeFormatter is the default TimeFormatter.

Jump to

Keyboard shortcuts

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