tint

package module
v0.0.0-...-77268b7 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2023 License: MIT Imports: 11 Imported by: 9

README

tint: 🌈 slog.Handler that writes tinted logs

Go Reference Go Report Card



[!NOTE] This is a fork of https://github.com/lmittmann/tint with custom colors

Package tint implements a zero-dependency slog.Handler that writes tinted (colorized) logs. Its output format is inspired by the zerolog.ConsoleWriter and slog.TextHandler.

The output format can be customized using Options which is a drop-in replacement for slog.HandlerOptions.

go get github.com/topi314/tint

Usage

w := os.Stderr

// create a new logger
logger := slog.New(tint.NewHandler(w, nil))

// set global logger with custom options
slog.SetDefault(slog.New(
    tint.NewHandler(w, &tint.Options{
        Level:      slog.LevelDebug,
        TimeFormat: time.Kitchen,
    }),
))
Customize Colors

Colors can be customized using the Options.LevelColors and Options.Colors attributes. See tint.Options for details.

// ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code
const (
    ansiFaint            = "\033[2m"
    ansiBrightRed        = "\033[91m"
    ansiBrightRedFaint   = "\033[91;2m"
    ansiBrightGreen      = "\033[92m"
    ansiBrightYellow     = "\033[93m"
    ansiBrightYellowBold = "\033[93;1m"
    ansiBrightBlueBold   = "\033[94;1m"
    ansiBrightMagenta    = "\033[95m"
)

// create a new logger with custom colors
w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        LevelColors: map[slog.Level]string{
            slog.LevelDebug: ansiBrightMagenta,
            slog.LevelInfo:  ansiBrightGreen,
            slog.LevelWarn:  ansiBrightYellow,
            slog.LevelError: ansiBrightRed,
        },
		Colors: map[tint.Kind]string{
            tint.KindTime:            ansiBrightYellowBold,
            tint.KindSourceFile:      ansiFaint,
            tint.KindSourceSeparator: ansiFaint,
            tint.KindSourceLine:      ansiFaint,
            tint.KindMessage:         ansiBrightBlueBold,
            tint.KindKey:             ansiFaint,
            tint.KindSeparator:       ansiFaint,
            tint.KindValue:           ansiBrightBlueBold,
            tint.KindErrorKey:        ansiBrightRedFaint,
            tint.KindErrorSeparator:  ansiBrightRedFaint,
            tint.KindErrorValue:      ansiBrightRed,
		},
    }),
)
Customize Attributes

ReplaceAttr can be used to alter or drop attributes. If set, it is called on each non-group attribute before it is logged. See slog.HandlerOptions for details.

// create a new logger that doesn't write the time
w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
            if a.Key == slog.TimeKey && len(groups) == 0 {
                return slog.Attr{}
            }
            return a
        },
    }),
)
Automatically Enable Colors

Colors are enabled by default and can be disabled using the Options.NoColor attribute. To automatically enable colors based on the terminal capabilities, use e.g. the go-isatty package.

w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        NoColor: !isatty.IsTerminal(w.Fd()),
    }),
)
Windows Support

Color support on Windows can be added by using e.g. the go-colorable package.

w := os.Stderr
logger := slog.New(
    tint.NewHandler(colorable.NewColorable(w), nil),
)

Documentation

Overview

Package tint implements a zero-dependency slog.Handler that writes tinted (colorized) logs. The output format is inspired by the zerolog.ConsoleWriter and slog.TextHandler.

The output format can be customized using Options, which is a drop-in replacement for slog.HandlerOptions.

Customizing Colors

Colors can be customized using the `Options.LevelColors` and `Options.Colors` attributes. See tint.Options for details.

// ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code
const (
    ansiFaint            = "\033[2m"
    ansiBrightRed        = "\033[91m"
    ansiBrightRedFaint   = "\033[91;2m"
    ansiBrightGreen      = "\033[92m"
    ansiBrightYellow     = "\033[93m"
    ansiBrightYellowBold = "\033[93;1m"
    ansiBrightBlueBold   = "\033[94;1m"
    ansiBrightMagenta    = "\033[95m"
)

// create a new logger with custom colors
w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        LevelColors: map[slog.Level]string{
            slog.LevelDebug: ansiBrightMagenta,
            slog.LevelInfo:  ansiBrightGreen,
            slog.LevelWarn:  ansiBrightYellow,
            slog.LevelError: ansiBrightRed,
        },
		Colors: map[tint.Kind]string{
            tint.KindTime:            ansiBrightYellowBold,
            tint.KindSourceFile:      ansiFaint,
            tint.KindSourceSeparator: ansiFaint,
            tint.KindSourceLine:      ansiFaint,
            tint.KindMessage:         ansiBrightBlueBold,
            tint.KindKey:             ansiFaint,
            tint.KindSeparator:       ansiFaint,
            tint.KindValue:           ansiBrightBlueBold,
            tint.KindErrorKey:        ansiBrightRedFaint,
            tint.KindErrorSeparator:  ansiBrightRedFaint,
            tint.KindErrorValue:      ansiBrightRed,
		},
    }),
)

Customize Attributes

Options.ReplaceAttr can be used to alter or drop attributes. If set, it is called on each non-group attribute before it is logged. See slog.HandlerOptions for details.

w := os.Stderr
logger := slog.New(
	tint.NewHandler(w, &tint.Options{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}),
)

Automatically Enable Colors

Colors are enabled by default and can be disabled using the Options.NoColor attribute. To automatically enable colors based on the terminal capabilities, use e.g. the go-isatty package.

w := os.Stderr
logger := slog.New(
	tint.NewHandler(w, &tint.Options{
		NoColor: !isatty.IsTerminal(w.Fd()),
	}),
)

Windows Support

Color support on Windows can be added by using e.g. the go-colorable package.

w := os.Stderr
logger := slog.New(
	tint.NewHandler(colorable.NewColorable(w), nil),
)
Example
package main

import (
	"errors"
	"log/slog"
	"os"
	"time"

	"github.com/topi314/tint"
)

func main() {
	slog.SetDefault(slog.New(tint.NewHandler(os.Stderr, &tint.Options{
		Level:      slog.LevelDebug,
		TimeFormat: time.Kitchen,
	})))

	slog.Info("Starting server", "addr", ":8080", "env", "production")
	slog.Debug("Connected to DB", "db", "myapp", "host", "localhost:5432")
	slog.Warn("Slow request", "method", "GET", "path", "/users", "duration", 497*time.Millisecond)
	slog.Error("DB connection lost", tint.Err(errors.New("connection reset")), "db", "myapp")
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Err

func Err(err error) slog.Attr

Err returns slog.Any("err", err)

func NewHandler

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

NewHandler creates a slog.Handler that writes tinted logs to Writer w, using the default options. If opts is nil, the default options are used.

Types

type Kind

type Kind int
const (
	KindTime Kind = iota
	KindSourceFile
	KindSourceSeparator
	KindSourceLine
	KindMessage
	KindKey
	KindSeparator
	KindValue
	KindErrorKey
	KindErrorSeparator
	KindErrorValue
)

type Options

type Options struct {
	// Enable source code location (Default: false)
	AddSource bool

	// Minimum level to log (Default: slog.LevelInfo)
	Level slog.Leveler

	// ReplaceAttr is called to rewrite each non-group attribute before it is logged.
	// See https://pkg.go.dev/log/slog#HandlerOptions for details.
	ReplaceAttr func(groups []string, attr slog.Attr) slog.Attr

	// Time format (Default: time.StampMilli)
	TimeFormat string

	// Disable color (Default: false)
	NoColor bool

	// Level colors (Default: debug: faint, info: green, warn: yellow, error: red)
	LevelColors map[slog.Level]string

	// Colors of certain parts of the log message
	Colors map[Kind]string
}

Options for a slog.Handler that writes tinted logs. A zero Options consists entirely of default values.

Options can be used as a drop-in replacement for slog.HandlerOptions.

Jump to

Keyboard shortcuts

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