clog

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2023 License: Apache-2.0 Imports: 15 Imported by: 17

README

clog

Customizable slog.Handler for console.

package main

import (
	"github.com/m-mizutani/clog"
	"log/slog"
)

func main() {
	handler := clog.New(
		clog.WithColor(true),
		clog.WithSource(true),
	)
	logger := slog.New(handler)

	logger.Info("hello, world!", slog.String("foo", "bar"))
	logger.Warn("What?", slog.Group("group1", slog.String("foo", "bar")))
	logger.WithGroup("hex").Error("Ouch!", slog.Int("num", 123))
}
Screenshot 2023-06-11 at 10 41 29

Options

  • WithWriter: Output writer. Default is os.Stdout.
  • WithLevel: Log level. Default is slog.LevelInfo.
  • WithTimeFmt: Time format string. Default is 15:04:05.000.
  • WithColor: Enable colorized output. Default will be changed by terminal's color support.
  • WithColorMap: Color map for each log level. Default is clog.DefaultColorMap. See ColorMap section for more detail.
  • WithSource: Enable source code location. Default is false.
  • WithReplaceAttr: Replace attribute value. It's same with slog.ReplaceAttr in slog.HandlerOptions.
  • WithTemplate: Template string. See Template section for more detail.
  • WithAttrPrinter: Attribute printer. Default is clog.LinearPrinter. See AttrPrinter section for more detail.
ColorMap

You can customize color map for each handler with clog.ColorMap. Default is clog.DefaultColorMap. If the fields is nil or not set, default color will be used.

  • LogLevel: You can set color for each log level. If not set, default color LogLevelDefault will be used.
  • LogLevelDefault: Default color for log level.
  • Time: Color for time string.
  • Message: Color for log message string.
  • AttrKey: Color for attribute key string. It's applied or not depends on AttrPrinter.
  • AttrValue: Color for attribute value string. It's applied or not depends on AttrPrinter.
Template

Template can be used to customize log format. A developer can use following variables in template string.

  • .Time: Time string. Format is specified WithTimeFmt.
  • .Elapsed: Duration from the start of the program
  • .Level: Log level string. e.g. INFO, WARN, ERROR
  • .Message: Log message
  • .FileName: A file name of the source code that calls logger. It is empty if WithSource is not specified
  • .FilePath: A full file path of the source code that calls logger. It is empty if WithSource is not specified.
  • .FileLine: A line number of the source code that calls logger. It is empty if WithSource is not specified
  • .FuncName A function name of the source code that calls logger. It is empty if WithSource is not specified

Default is clog.DefaultTemplate.

AttrPrinter

AttrPrinter is an interface designed for customizing the way attributes are printed. By default, clog.LinearPrinter is used.

  • LinearPrinter: Print attributes in a linear way.
  • PrettyPrinter: Print attributes with pp package.
  • IndentPrinter: Print attributes with indent like YAML format.

Full example is here.

func main() {
	user := User{
		Name:  "mizutani",
		Email: "mizutani@hey.com",
	}

	store := Store{
		Name:    "Jiro",
		Address: "Tokyo",
		Phone:   "123-456-7890",
	}
	group := slog.Group("info", slog.Any("user", user), slog.Any("store", store))

	linearHandler := clog.New(clog.WithPrinter(clog.LinearPrinter))
	slog.New(linearHandler).Info("by LinearPrinter", group)

	prettyHandler := clog.New(clog.WithPrinter(clog.PrettyPrinter))
	slog.New(prettyHandler).Info("by PrettyPrinter", group)

	indentHandler := clog.New(clog.WithPrinter(clog.IndentPrinter))
	slog.New(indentHandler).Info("by IndentHandler", group)
}
Screenshot 2023-06-11 at 10 39 26

License

Apache License 2.0

Documentation

Index

Constants

View Source
const (
	TemplateStandardWithElapsed = `{{.Elapsed | printf "%8.3f" }} {{.Level}} {{ if .FileName }}[{{.FileName}}:{{.FileLine}}] {{ end }}{{.Message}} `
	TemplateStandardWithTime    = `{{.Timestamp}} {{.Level}} {{ if .FileName }}[{{.FileName}}:{{.FileLine}}] {{ end }}{{.Message}} `
	TemplateStandard            = `{{.Level}} {{ if .FileName }}[{{.FileName}}:{{.FileLine}}] {{ end }}{{.Message}} `
	DefaultTemplate             = TemplateStandardWithTime
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AttrPrinter

type AttrPrinter interface {
	Enter(group string)
	Exit(group string)
	Print(attr slog.Attr)
}

func IndentPrinter

func IndentPrinter(w io.Writer, cfg *config) AttrPrinter

IndentPrinter is a printer that prints attributes in a indented format.

func LinearPrinter

func LinearPrinter(w io.Writer, cfg *config) AttrPrinter

LinearPrinter is a printer that prints attributes in a linear format.

func PrettyPrinter

func PrettyPrinter(w io.Writer, cfg *config) AttrPrinter

PrettyPrinter is a printer that prints attributes in a pretty format.

type ColorMap

type ColorMap struct {
	Level        map[slog.Level]*color.Color
	LevelDefault *color.Color

	Time    *color.Color
	Message *color.Color

	// Whether AttrKey and AttrValue color settings are used or not depends on the AttrPrinter
	AttrKey   *color.Color
	AttrValue *color.Color
}

type Handler

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

Handler is a slog handler that writes logs to an io.Writer.

func New

func New(options ...Option) *Handler

New creates a new handler.

func (*Handler) Enabled

func (x *Handler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*Handler) Handle

func (x *Handler) Handle(ctx context.Context, record slog.Record) error

Handle implements slog.Handler.

func (*Handler) WithAttrs

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

WithAttrs implements slog.Handler.

func (*Handler) WithGroup

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

WithGroup implements slog.Handler.

type Log

type Log struct {

	// Timestamp is a time when the log is recorded. Format can be specified by WithTimeFmt.
	Timestamp string

	// Elapsed is duration from the start of the program.
	Elapsed float64

	// Level is a log level. It is one of "DEBUG", "INFO", "WARN", "ERROR", "FATAL".
	Level string

	// Message is a log message.
	Message string

	// FileName is a file name of the source code that calls logger. It is empty if WithSource is not specified.
	FileName string

	// FilePath is a full file path of the source code that calls logger. It is empty if WithSource is not specified.
	FilePath string

	// FileLine is a line number of the source code that calls logger. It is empty if WithSource is not specified.
	FileLine int

	// FuncName is a function name of the source code that calls logger. It is empty if WithSource is not specified.
	FuncName string
	// contains filtered or unexported fields
}

func (*Log) Coloring

func (x *Log) Coloring(colors *ColorMap) *Log

type Option

type Option func(*config)

func WithColor

func WithColor(color bool) Option

WithColor enables or disables color output. The default is enabled.

func WithColorMap

func WithColorMap(colors *ColorMap) Option

WithColorMap sets the color set for the handler.

func WithLevel

func WithLevel(level slog.Leveler) Option

WithLevel sets the minimum level for the handler. The default is LevelInfo.

func WithPrinter

func WithPrinter(printer func(io.Writer, *config) AttrPrinter) Option

WithPrinter sets the printer for printing attributes. The default is LinearPrinter.

func WithReplaceAttr

func WithReplaceAttr(replaceAttr func(groups []string, a slog.Attr) slog.Attr) Option

WithReplaceAttr sets the function for replacing attributes. The default is nil.

func WithSource

func WithSource(addSource bool) Option

WithSource enables or disables adding the source attribute. The default is disable.

func WithTemplate

func WithTemplate(tmpl *template.Template) Option

WithTemplate sets the template for the handler. The default is DefaultTemplate. This option executes dry run and panics if the template is invalid.

func WithTimeFmt

func WithTimeFmt(timeFmt string) Option

WithTimeFmt sets the time format for the time attribute. The default is "2006-01-02 15:04:05".

func WithWriter

func WithWriter(w io.Writer) Option

WithWriter sets the writer for the handler. The default is os.Stdout.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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