console

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2025 License: MIT Imports: 14 Imported by: 1

README

console-slog

Go Reference license Build codecov Go Report Card

A handler for slog that prints colorized logs, similar to zerolog's console writer output without sacrificing performances.

Installation

go get github.com/ansel1/console-slog@latest

Example

package main

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

	"github.com/ansel1/console-slog"
)

func main() {
	logger := slog.New(
		console.NewHandler(os.Stderr, &console.HandlerOptions{Level: slog.LevelDebug}),
	)
	slog.SetDefault(logger)
	slog.Info("Hello world!", "foo", "bar")
	slog.Debug("Debug message")
	slog.Warn("Warning message")
	slog.Error("Error message", "err", errors.New("the error"))

	logger = logger.With("foo", "bar").
		WithGroup("the-group").
		With("bar", "baz")

	logger.Info("group info", "attr", "value")
}

output

When setting console.HandlerOptions.AddSource to true:

console.NewHandler(os.Stderr, &console.HandlerOptions{Level: slog.LevelDebug, AddSource: true})

output-with-source

Performances

See benchmark file for details.

The handler itself performs quite well compared to std-lib's handlers. It does no allocation. It is generally faster then slog.TextHandler, and a little slower than slog.JSONHandler.

Credit

This is a forked and heavily modified variant of github.com/phsym/console-slog.

Documentation

Index

Constants

View Source
const (
	Reset = iota
	Bold
	Faint
	Italic
	Underline
	CrossedOut = 9
)
View Source
const (
	Black = iota + 30
	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	Gray
)
View Source
const (
	BrightBlack = iota + 90
	BrightRed
	BrightGreen
	BrightYellow
	BrightBlue
	BrightMagenta
	BrightCyan
	White
)

Variables

View Source
var ResetMod = ToANSICode(Reset)

Functions

This section is empty.

Types

type ANSIMod

type ANSIMod string

func ToANSICode

func ToANSICode(modes ...int) ANSIMod

func (ANSIMod) String

func (c ANSIMod) String() string

type Handler

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

func NewHandler

func NewHandler(out io.Writer, opts *HandlerOptions) *Handler

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

func (*Handler) Enabled

func (h *Handler) Enabled(_ context.Context, l slog.Level) bool

Enabled implements slog.Handler.

func (*Handler) Handle

func (h *Handler) Handle(ctx context.Context, rec slog.Record) error

func (*Handler) WithAttrs

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

WithAttrs implements slog.Handler.

func (*Handler) WithGroup

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

WithGroup implements slog.Handler.

type HandlerOptions

type HandlerOptions struct {
	// AddSource causes the handler to compute the source code position
	// of the log statement and add a SourceKey attribute to the output.
	AddSource bool

	// Level reports the minimum record level that will be logged.
	// The handler discards records with lower levels.
	// If Level is nil, the handler assumes LevelInfo.
	// The handler calls Level.Level for each record processed;
	// to adjust the minimum level dynamically, use a LevelVar.
	Level slog.Leveler

	// Disable colorized output
	NoColor bool

	// TimeFormat is the format used for time.DateTime
	TimeFormat string

	// Theme defines the colorized output using ANSI escape sequences
	Theme Theme

	// ReplaceAttr is called to rewrite each non-group attribute before it is logged.
	// See [slog.HandlerOptions]
	ReplaceAttr func(groups []string, a slog.Attr) slog.Attr

	// TruncateSourcePath shortens the source file path, if AddSource=true.
	// If 0, no truncation is done.
	// If >0, the file path is truncated to that many trailing path segments.
	// For example:
	//
	//     users.go:34						// TruncateSourcePath = 1
	//     models/users.go:34				// TruncateSourcePath = 2
	//     ...etc
	TruncateSourcePath int

	// HeaderFormat specifies the format of the log header.
	//
	// The default format is "%t %l %[source]h > %m".
	//
	// The format is a string containing verbs, which are expanded as follows:
	//
	//	%t	       timestamp
	//	%l	       abbreviated level (e.g. "INF")
	//	%L	       level (e.g. "INFO")
	//	%m	       message
	//	%s	       source (if omitted, source is just handled as an attribute)
	//	%a	       attributes
	//	%[key]h	   header with the given key.
	//  %{         group open
	//  %(style){  group open with style - applies the specified Theme style to any strings in the group
	//  %}         group close
	//
	// Headers print the value of the attribute with the given key, and remove that
	// attribute from the end of the log line.
	//
	// Headers can be customized with width and alignment modifiers,
	// similar to fmt.Printf verbs. For example:
	//
	//	%[key]10h		// left-aligned, width 10
	//	%[key]-10h		// right-aligned, width 10
	//
	// Groups will omit their contents if all the fields in that group are omitted.  For example:
	//
	//	"%l %{%[logger]h %[source]h > %} %m"
	//
	// will print "INF main main.go:123 > msg" if the either the logger or source attribute is present.  But if the
	// both attributes are not present, or were elided by ReplaceAttr, then this will print "INF msg".  Groups can
	// be nested.
	//
	// Groups can also be styled using the Theme styles by specifying a style in parentheses after the percent sign:
	//
	//	"%l %(source){ %[logger]h %} %m"
	//
	// will apply the source style from the Theme to the fixed strings in the group. By default, the Header style is used.
	//
	// Whitespace is generally merged to leave a single space between fields.  Leading and trailing whitespace is trimmed.
	//
	// Examples:
	//
	//	"%t %l %m"                         // timestamp, level, message
	//	"%t [%l] %m"                       // timestamp, level in brackets, message
	//	"%t %l:%m"                         // timestamp, level:message
	//	"%t %l %[key]h %m"                 // timestamp, level, header with key "key", message
	//	"%t %l %[key1]h %[key2]h %m"       // timestamp, level, header with key "key1", header with key "key2", message
	//	"%t %l %[key]10h %m"               // timestamp, level, header with key "key" and width 10, message
	//	"%t %l %[key]-10h %m"              // timestamp, level, right-aligned header with key "key" and width 10, message
	//	"%t %l %L %m"                      // timestamp, abbreviated level, non-abbreviated level, message
	//	"%t %l %L- %m"                     // timestamp, abbreviated level, right-aligned non-abbreviated level, message
	//	"%t %l %m string literal"          // timestamp, level, message, and then " string literal"
	//	"prefix %t %l %m suffix"           // "prefix ", timestamp, level, message, and then " suffix"
	//	"%% %t %l %m"                      // literal "%", timestamp, level, message
	//  "%{[%t]%} %{[%l]%} %m"             // timestamp and level in brackets, message, brackets will be omitted if empty
	HeaderFormat string
}

HandlerOptions are options for a ConsoleHandler. A zero HandlerOptions consists entirely of default values. ReplaceAttr works identically to slog.HandlerOptions.ReplaceAttr

type Theme

type Theme struct {
	Name           string
	Timestamp      ANSIMod
	Header         ANSIMod
	Source         ANSIMod
	Message        ANSIMod
	MessageDebug   ANSIMod
	AttrKey        ANSIMod
	AttrValue      ANSIMod
	AttrValueError ANSIMod
	LevelError     ANSIMod
	LevelWarn      ANSIMod
	LevelInfo      ANSIMod
	LevelDebug     ANSIMod
}

func NewBrightTheme

func NewBrightTheme() Theme

func NewDefaultTheme

func NewDefaultTheme() Theme

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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