xlog

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2023 License: MIT Imports: 16 Imported by: 1

README

xlog - yet another "log/slog" backend/frontend wrappers and tinted 🌈 slog.Handler

Package xlog implements some wrappers to work with structured logger slog and classic simple logger log too.

Code of xlog.TintHandler based on tint.

go get github.com/azorg/xlog

Usage

  conf := NewConf()                 // create default config (look xlog.Conf for details)
  conf.Level = "trace"              // set logger level
  conf.Tint = true                  // select tinted logger
  conf.Src = true                   // add source file:line to log
  conf.TimeTint = "15:04:05.999999" // add custom timestamp
  x := New(conf)                    // create xlog with TintHandler
  x.SetDefault()                    // set default xlog
	
  err := errors.New("some error")
  count := 12345

  xlog.Trace("Tinted logger xlog.Trace()", "level", conf.Level)
  xlog.Debug("Tinted logger xlog.Debug()")
  xlog.Info("Tinted logger xlog.Info()", "count", count)

  x.Notice("Tinted logger x.Notice()")
  x.Warn("Tinted logger x.Warn()")
  x.Error("Tinted logger x.Error()", Err(err))
	
  sl := x.Slog() // *slog.Logger may used too
  sl.Info("Tinted logger is *slog.Logger sl.Info()", "str", "some string")

Look xlog_test.go for more examples.

Documentation

Overview

Пакет xlog реализует простую надстройку на стандартными логерами log и slog.

Логер slog включен в стандартную поставку Go начиная с версии 1.21 ("log/slog"). До этого логер представлен экспериментальным пакетом "golang.org/x/exp/slog". Экспериментальный пакет содержит ошибки (ждем когда исправят, но пока не спешат).

Структуры данных:

Conf - Обобщенная структура конфигурации логера, имеет JSON тэги

Xlog - Структура/обёртка над slog для добавления методов типа Debugf/Noticef/Errorf/Trace

Функции настройки конфигурации:

NewConf() - заполнить обобщенную структуру конфигурации логера значениями по умолчанию

SetupLog() - настроить стандартный логер в соответствии с заданной структурой конфигурации

NewLog() - создать стандартный логер log.Logger в соответствии со структурой конфигурации

NewSlog() - создать структурированный логер slog.Logger в соответствии со структурой конфигурации

Setup() - настроить стандартный и структурированный логеры по умолчанию в соответствии с структурой конфигурации

GetLevel() - вернуть текущий уровень журналирования

GetLvl() - вернуть текущий уровень журналирования в виде строки

Функции для работы с надстройкой Xlog:

Default() - Создать логер Xlog на основе исходного slog.Deafult()

Current() - Вернуть текущий глобальный логер Xlog

Slog() - Вернуть текущий глобальный логер slog.Logger

X() - Создать логер Xlog на основе логера slog

New() - Cоздать новый логер Xlog с заданными параметрами конфигурации

Методы для работы с Xlog:

Slog() - Обратное преобразование Xlog -> *slog.Logger

SetDefault() - Установить логер как xlog по умолчанию

SetDefaultLogs() - Установить логер как log/slog/xlog по умолчанию

Методы для использования Xlog с дополнительными уровнями:

Log(level Level, msg string, args ...any)
Trace(msg string, args ...any)
Debug(msg string, args ...any)
Info(msg string, args ...any)
Notice(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
Fatal(msg string, args ...any)
Panic(msg string)

Logf(evel Level, format string, args ...any)
Tracef(format string, args ...any)
Debugf(format string, args ...any)
Infof(format string, args ...any)
Noticef(format string, args ...any)
Warnf(format string, args ...any)
Errorf(format string, args ...any)
Fatalf(format string, args ...any)

Примечание: имеются аналогичные глобальные функции в пакете для использования глобального логера.

Index

Constants

View Source
const (
	AnsiReset            = "\033[0m"       // All attributes off
	AnsiFaint            = "\033[2m"       // Decreased intensity
	AnsiResetFaint       = "\033[22m"      // Normal color (reset faint)
	AnsiRed              = "\033[31m"      // Red
	AnsiGreen            = "\033[32m"      // Green
	AnsiYellow           = "\033[33m"      // Yellow
	AnsiBlue             = "\033[34m"      // blue
	AnsiMagenta          = "\033[35m"      // Magenta
	AnsiCyan             = "\033[36m"      // Cyan
	AnsiWhile            = "\033[37m"      // While
	AnsiBrightRed        = "\033[91m"      // Bright Red
	AnsiBrightRedNoFaint = "\033[91;22m"   // Bright Red and normal intensity
	AnsiBrightGreen      = "\033[92m"      // Bright Green
	AnsiBrightYellow     = "\033[93m"      // Bright Yellow
	AnsiBrightBlue       = "\033[94m"      // Bright Blue
	AnsiBrightMagenta    = "\033[95m"      // Bright Magenta
	AnsiBrightCyan       = "\033[96m"      // Bright Cyan
	AnsiBrightWight      = "\033[97m"      // Bright White
	AnsiBrightRedFaint   = "\033[91;2m"    // Bright Red and decreased intensity
	AnsiWhiteOnMagenta   = "\033[37;45;1m" // Bright White on Magenta background
	AnsiWhiteOnRed       = "\033[37;41;1m" // Bright White on Red backgroun
)

ANSI modes

View Source
const (
	AnsiTrace  = AnsiBrightBlue
	AnsiDebug  = AnsiBrightCyan
	AnsiInfo   = AnsiBrightGreen
	AnsiNotice = AnsiBrightMagenta
	AnsiWarn   = AnsiBrightYellow
	AnsiError  = AnsiBrightRed
	AnsiFatal  = AnsiWhiteOnMagenta
	AnsiPanic  = AnsiWhiteOnRed
)

Level keys ANSI colors

View Source
const (
	AnsiTime   = AnsiFaint
	AnsiSource = AnsiFaint
	AnsiKey    = AnsiFaint
	AnsiErrKey = AnsiBrightRedFaint
	AnsiErrVal = AnsiBrightRedNoFaint
)

Log part colors

View Source
const (
	FILE      = "stdout" // log file path OR stdout/stderr
	FILE_MODE = "0640"   // log file mode (if FILE is not stdout/stderr)
	LEVEL     = LvlInfo  // log level (trace/debug/info/warn/error/fatal/silent)
	SLOG      = false    // use slog insted standart log (slog.TextHandler)
	JSON      = false    // use JSON log (slog.JSONHandelr)
	TINT      = false    // use tinted (colorized) log (xlog.TintHandler)
	TIME      = false    // add time stamp
	TIME_US   = false    // us time stamp (only if SLOG=false)
	TIME_TINT = ""       // tinted log time format (~time.Kitchen, time.DateTime)
	SRC       = false    // log file name and line number
	SRC_LONG  = false    // log long file path
	NO_LEVEL  = false    // don't print log level tag to log (~level="INFO")
	NO_COLOR  = false    // don't use tinted colors (only if Tint=true)
	PREFIX    = ""       // add prefix to standart log (SLOG=false)
	ADD_KEY   = ""       // add key to structured log (SLOG=true)
	ADD_VALUE = ""       // add value to structured log (SLOG=true
)

Default logger configure

View Source
const (
	// Add addition log level marks (TRACE/NOTICE/FATAL/PANIC)
	ADD_LEVELS = true

	// Log file mode in error configuration
	DEFAULT_FILE_MODE = 0600 // read/write only for owner for more secure

	// Set false for go > 1.21 with log/slog
	OLD_SLOG_FIX = false // runtime.Version() < go1.21.0
)
View Source
const (
	LevelTrace  = Level(slog.Level(-8))  // TRACE  (-8)
	LevelDebug  = Level(slog.LevelDebug) // DEBUG  (-4)
	LevelInfo   = Level(slog.LevelInfo)  // INFO   (0)
	LevelNotice = Level(slog.Level(2))   // NOTICE (2)
	LevelWarn   = Level(slog.LevelWarn)  // WARN   (4)
	LevelError  = Level(slog.LevelError) // ERROR  (8)
	LevelFatal  = Level(slog.Level(12))  // FATAL  (12)
	LevelPanic  = Level(slog.Level(16))  // PANIC  (16)
	LevelSilent = Level(slog.Level(20))  // SILENT (20)
)

Log levels delivered from slog.Level

View Source
const (
	LvlTrace  Lvl = "trace"
	LvlDebug      = "debug"
	LvlInfo       = "info"
	LvlNotice     = "notice"
	LvlWarn       = "warn"
	LvlError      = "error"
	LvlFatal      = "fatal"
	LvlPanic      = "panic"
	LvlSilent     = "silent"
)
View Source
const (
	LabelTrace  = "TRACE"
	LabelDebug  = "DEBUG"
	LabelInfo   = "INFO"
	LabelNotice = "NOTICE"
	LabelWarn   = "WARN"
	LabelError  = "ERROR"
	LabelFatal  = "FATAL"
	LabelPanic  = "PANIC"
	LabelSilent = "SILENT"
)

Log level tags

View Source
const (
	// Time OFF
	TIME_OFF = ""

	// Default time format of standart logger
	STD_TIME = "2006/01/02 15:04:05"

	// Default time format of standart logger + microseconds
	STD_TIME_US = "2006/01/02 15:04:05.999999"

	// Default time format of standart logger + milliseconds
	STD_TIME_MS = "2006/01/02 15:04:05.999"

	// RFC3339 time format + nanoseconds (slog.TextHandler by default)
	RFC3339Nano = time.RFC3339Nano // "2006-01-02T15:04:05.999999999Z07:00"

	// RFC3339 time format + microseconds
	RFC3339Micro = "2006-01-02T15:04:05.999999Z07:00"

	// RFC3339 time format + milliseconds
	RFC3339Milli = "2006-01-02T15:04:05.999Z07:00"

	// Time only format + microseconds
	TimeOnlyMicro = "15:04:05.999999"

	// Time only format + milliseconds
	TimeOnlyMilli = "15:04:05.999"

	// Default (recomented) time format wuth milliseconds
	DEFAULT_TIME_FORMAT = STD_TIME_MS

	// Default (recomented) time format witn microseconds
	DEFAULT_TIME_FORMAT_US = STD_TIME_US
)

Time formats

View Source
const BUFFER_DEFAULT_CAP = 1024
View Source
const DEFAULT_LEVEL = LevelInfo
View Source
const ERR_KEY = "err"

Variables

This section is empty.

Functions

func AddOpt

func AddOpt(opt *Opt, conf *Conf)

Add parsed command line options to logger config

func Debug

func Debug(msg string, args ...any)

Debug logs at LevelDebug with default Xlog

func Debugf

func Debugf(format string, args ...any)

Debugf logs at LevelDebug as standart logger with default Xlog

func Err

func Err(err error) slog.Attr

Err() returns slog.Attr with "err" key if err != nil

func Error

func Error(msg string, args ...any)

Error logs at LevelError with default Xlog

func Errorf

func Errorf(format string, args ...any)

Errorf logs at LevelError as standart logger with default Xlog

func Fatal

func Fatal(msg string, args ...any)

Fatal logs at LevelFatal with default Xlog and os.Exit(1)

func Fatalf

func Fatalf(format string, args ...any)

Fatalf logs at LevelFatal as standart logger with default Xlog and os.Exit(1)

func Info

func Info(msg string, args ...any)

Info logs at LevelInfo with default Xlog

func Infof

func Infof(format string, args ...any)

Infof logs at LevelInfo as standart logger with default Xlog

func Log

func Log(level Level, msg string, args ...any)

Log logs at given level with default Xlog

func Logf

func Logf(level Level, format string, args ...any)

Logf logs at given level as standart logger with default Xlog

func NewLog

func NewLog(conf Conf) *log.Logger

Create new configured standart logger

func NewSlog

func NewSlog(conf Conf) *slog.Logger

Create new configures structured logger (default/text/JSON/Tinted handler)

func Notice

func Notice(msg string, args ...any)

Notice logs at LevelNotice with default Xlog

func Noticef

func Noticef(format string, args ...any)

Noticef logs at LevelNotice as standart logger with default Xlog

func Panic

func Panic(msg string)

Panic logs at LevelPanic with default Xlog and panic

func Setup

func Setup(conf Conf)

Setup standart and structured default global loggers

func SetupLog

func SetupLog(logger *log.Logger, conf Conf)

Setup standart simple logger

func Slog

func Slog() *slog.Logger

Return current *slog.Logger

func String

func String(key, value string) slog.Attr

String return slog.Attr if key != "" and value != ""

func Trace

func Trace(msg string, args ...any)

Trace logs at LevelTrace with default Xlog

func Tracef

func Tracef(format string, args ...any)

Tracef logs at LevelTrace as standart logger with default Xlog

func Warn

func Warn(msg string, args ...any)

Warn logs at LevelWarn with default Xlog

func Warnf

func Warnf(format string, args ...any)

Warnf logs at LevelWarn as standart logger with default Xlog

Types

type Buffer

type Buffer []byte

func NewBuffer

func NewBuffer() *Buffer

func (*Buffer) Free

func (b *Buffer) Free()

func (*Buffer) Write

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

func (*Buffer) WriteByte

func (b *Buffer) WriteByte(char byte) error

func (*Buffer) WriteString

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

func (*Buffer) WriteStringIf

func (b *Buffer) WriteStringIf(ok bool, str string) (int, error)

type Conf

type Conf struct {
	File     string `json:"file"`      // log file path OR stdout/stderr
	FileMode string `json:"file-mode"` // log file mode (if File is not stdout/stderr)
	Level    Lvl    `json:"level"`     // log level (trace/debug/info/warn/error/fatal/silent)
	Slog     bool   `json:"slog"`      // use slog insted standart log (slog.TextHandler)
	JSON     bool   `json:"json"`      // use JSON log (slog.JSONHandler)
	Tint     bool   `json:"tint"`      // use tinted (colorized) log (xlog.TintHandler)
	Time     bool   `json:"time"`      // add timestamp
	TimeUS   bool   `json:"time-us"`   // us time stamp (only if Slog=false or Tint=true and TintTime="")
	TimeTint string `json:"time-tint"` // tinted log time format (like time.Kitchen, time.DateTime)
	Src      bool   `json:"src"   `    // log file name and line number
	SrcLong  bool   `json:"src-long"`  // log long file path
	NoLevel  bool   `json:"no-level"`  // don't print log level tag to log (~level="INFO")
	NoColor  bool   `json:"no-color"`  // disable tinted colors (only if Tint=true)
	Prefix   string `json:"preifix"`   // add prefix to standart log (log=false)
	AddKey   string `json:"add-key"`   // add key to structured log (Slog=true)
	AddValue string `json:"add-value"` // add value to structured log (Slog=true
}

Logger configure structure

func NewConf

func NewConf() Conf

Create default logger structure

type Level

type Level slog.Level

xlog level delivered from slog.Level, implements slog.Leveler interface

func GetLevel

func GetLevel() Level

Return current log level as int (slog.Level)

func ParseLvl

func ParseLvl(lvl Lvl) Level

Parse Lvl (Lvl -> Level)

func (Level) ColorString

func (l Level) ColorString() string

ColorString() returns a color label for the level

func (Level) Level

func (l Level) Level() slog.Level

Level() returns the receiver (it implements slog.Leveler interface)

func (Level) String

func (l Level) String() string

String() returns a label for the level

type Lvl

type Lvl string

Log level as string for setup

func GetLvl

func GetLvl() Lvl

Return current log level as string (xlog.Lvl)

func ParseLevel

func ParseLevel(level Level) Lvl

Parse Level (Level -> Lvl)

type Opt

type Opt struct {
	LogLvl  string // log level (trace/debug/info/warn/error/fatal)
	SLog    bool   // use structured text loger (slog)
	JLog    bool   // use structured JSON loger (slog)
	TLog    bool   // use tinted (colorized) logger (tint)
	LogSrc  bool   // force log source file name and line number
	LogTime bool   // force add time to log
	LogTFmt string // log time format
}

Command line logger options

func NewOpt

func NewOpt() *Opt

Setup command line logger options Usage:

-log  <level> - Log level (trace/debug/info/notice/warm/error/fatal)
-slog         - Use structured text logger (slog)
-jlog         - Use structured JSON logger (slog)
-tlog         - Use tinted (colorized) logger (tint)
-lsrc         - Force log source file name and line number
-ltime        - Force add time to log

type TintHandler

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

Tinted (colorized) handler implements a slog.Handler

func NewTintHandler

func NewTintHandler(w io.Writer, opts *TintOptions) *TintHandler

Create new tinted (colorized) handler

func (*TintHandler) Enabled

func (h *TintHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled() implements slog.Handler interface

func (*TintHandler) Handle

func (h *TintHandler) Handle(_ context.Context, r slog.Record) error

Handle() implements slog.Handler interface

func (*TintHandler) WithAttrs

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

WithAttrs() implements slog.Handler interface

func (*TintHandler) WithGroup

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

WithGroup() implements slog.Handler interface

type TintOptions

type TintOptions struct {
	// Enable source code location
	AddSource bool

	// Log long file path (directory + file name)
	SourceLong bool

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

	// Off level keys
	NoLevel bool

	// 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
	TimeFormat string

	// Disable color
	NoColor bool
}

type Xlog

type Xlog struct{ *slog.Logger }

Xlog wrapper

func Current

func Current() Xlog

Return current Xlog

func Default

func Default() Xlog

Create Xlog based on default slog.Logger

func New

func New(conf Conf) Xlog

Create new custom Xlog

func X

func X(logger *slog.Logger) Xlog

Create Xlog based on *slog.Logger (*slog.Logger -> Xlog)

func (Xlog) Debug

func (x Xlog) Debug(msg string, args ...any)

Debug logs at LevelDebug

func (Xlog) Debugf

func (x Xlog) Debugf(format string, args ...any)

Debugf logs at LevelDebug as standart logger

func (Xlog) Error

func (x Xlog) Error(msg string, args ...any)

Error logs at LevelError

func (Xlog) Errorf

func (x Xlog) Errorf(format string, args ...any)

Errorf logs at LevelError as standart logger

func (Xlog) Fatal

func (x Xlog) Fatal(msg string, args ...any)

Fatal logs at LevelFatal and os.Exit(1)

func (Xlog) Fatalf

func (x Xlog) Fatalf(format string, args ...any)

Fatalf logs at LevelFatal as standart logger and os.Exit(1)

func (Xlog) Info

func (x Xlog) Info(msg string, args ...any)

Info logs at LevelInfo

func (Xlog) Infof

func (x Xlog) Infof(format string, args ...any)

Infof logs at LevelInfo as standart logger

func (Xlog) Log

func (x Xlog) Log(level Level, msg string, args ...any)

Log logs at given level

func (Xlog) Logf

func (x Xlog) Logf(level Level, format string, args ...any)

Logf logs at given level as standart logger

func (Xlog) Notice

func (x Xlog) Notice(msg string, args ...any)

Notice logs at LevelNotice

func (Xlog) Noticef

func (x Xlog) Noticef(format string, args ...any)

Noticef logs at LevelNotice as standart logger

func (Xlog) Panic

func (x Xlog) Panic(msg string)

Panic logs at LevelPanic and panic

func (Xlog) SetDefault

func (x Xlog) SetDefault()

Set Xlog logger as default xlog logger

func (Xlog) SetDefaultLogs

func (x Xlog) SetDefaultLogs()

Set Xlog logger as default xlog/log/slog loggers

func (Xlog) Slog

func (x Xlog) Slog() *slog.Logger

Extract *slog.Logger from Xlog (Xlog -> *slog.Logger)

func (Xlog) Trace

func (x Xlog) Trace(msg string, args ...any)

Trace logs at LevelTrace

func (Xlog) Tracef

func (x Xlog) Tracef(format string, args ...any)

Tracef logs at LevelTrace as standart logger

func (Xlog) Warn

func (x Xlog) Warn(msg string, args ...any)

Warn logs at LevelWarn

func (Xlog) Warnf

func (x Xlog) Warnf(format string, args ...any)

Warnf logs at LevelWarn as standart logger

Jump to

Keyboard shortcuts

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