tint

package module
v0.0.0-...-7df996e Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2025 License: MIT Imports: 13 Imported by: 0

README

tint: 🌈 slog.Handler that writes tinted logs

Go Reference Go Report Card

image



About this fork

This package is a fork of the original lmittmann/tint package. This fork adds support for color expressions (in MemoANSI format) in log messages.

Overview

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/phplego/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 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
        },
    }),
)
// create a new logger that writes all errors in red
w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
            if err, ok := a.Value.Any().(error); ok {
                aErr := tint.Err(err)
                aErr.Key = a.Key
                return aErr
            }
            return a
        },
    }),
)
Color Expressions

Color expression is a string that starts with @ followed by a color/background/boldness code and ends with {some text}. The format is @<color><bold><background>{text} for example @r!W{red bold on white background}. First symbol after @ is a color code, second symbol is an optional boldness flag (exclamation mark) and third symbol is an optional background color code.

// usage of color expressions
slog.Info("Example of @r{red color}")
slog.Info("Example of @R{bright red color}")
slog.Info("Example of @r!{red bold color}")
slog.Info("Example of @rW{red on white backgound}")
slog.Info("Example of @r!W{red bold on white backgound}")
slog.Info("Example of @*{Rainbow text}")

Supported color codes are:

Code Color Bright Variant Code Bright Color
k Black K Bright Black (Gray)
r Red R Bright Red
g Green G Bright Green
y Yellow Y Bright Yellow
b Blue B Bright Blue
m Magenta M Bright Magenta
c Cyan C Bright Cyan
w White W Bright White
  • * - Rainbow. Special color where each character has a different color.

See MemoANSI format for more details.

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.

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.

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
		},
	}),
)

Create a new logger that writes all errors in red:

w := os.Stderr
logger := slog.New(
	tint.NewHandler(w, &tint.Options{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if err, ok := a.Value.Any().(error); ok {
				aErr := tint.Err(err)
				aErr.Key = a.Key
				return aErr
			}
			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/phplego/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")

	slog.Info("Wow @W!r{ spam detected! } @g{please} @b!C{ do } something @*{awesome} link: @kG{ https://example.com }")
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Colorize

func Colorize(s string) string
Example
package main

import (
	"fmt"
	"strings"

	"github.com/phplego/tint"
)

func main() {
	colorsArr := []string{
		"k", "r", "g", "y", "b", "m", "c", "w",
		"K", "R", "G", "Y", "B", "M", "C", "W",
	}

	names := []string{
		"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
		"bright black", "bright red", "bright green", "bright yellow", "bright blue", "bright magenta", "bright cyan", "bright white",
	}

	println()
	println("Normal text:", strings.Repeat(" ", 22), "Bold text:")
	for i, k := range colorsArr {
		print(tint.Colorize(
			fmt.Sprintf("  %s - @%s{%-30s}", k, k, names[i]),
		))
		print(tint.Colorize(
			fmt.Sprintf("  %s! - @%s!{%s} \n", k, k, names[i]),
		))
	}

	// background colors
	println("\nWith background:")
	for _, b := range colorsArr {
		for _, k := range colorsArr {
			print(tint.Colorize(
				fmt.Sprintf("@%s!%s{ %s!%s } ", k, b, k, b),
			))
		}
		println()
	}

	// rainbow
	println()
	println(tint.Colorize("* - @*{Rainbow text where each letter has a different color}"))
	println()
}
Output:

func Err

func Err(err error) slog.Attr

Err returns a tinted (colorized) slog.Attr that will be written in red color by the tint.Handler. When used with any other slog.Handler, it behaves as

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 ColorizeWriter

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

func (ColorizeWriter) Write

func (w ColorizeWriter) Write(p []byte) (n int, err error)

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
}

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