xlog

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2024 License: MIT Imports: 17 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.

Tinted xlog

go get github.com/azorg/xlog

Usage

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

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

  x.Notice("Tinted logger x.Notice()", "lvl", x.GetLvl())
  x.Warn("Tinted logger x.Warn()", "level", int(x.GetLevel()))
  x.Error("Tinted logger x.Error()", Err(err))
  x.Crit("Tinted logger x.Crit()", Err(crit))
	
  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 тэги

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

Интерфейсы:

Xlogger - интерфейс к структуре Logger (приведен для наглядности API)

Leveler - интерфейс управления уровнем журналирования

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

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

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

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

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

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

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

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

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

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

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

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

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

X() - Создать логер на основе логера slog (для доступа к "сахарным" методам)

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

Методы для работы с Logger (методы интерфейса Xlogger):

  With() - Создать дочерний логгер с дополнительными атрибутами

  WithAttrs() - Создать дочерний логгер с дополнительными атрибутами

  WithGroup() - Создать дочерний логгер с группировкой ключей

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

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

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

	GetLevel() - получить текуший уровень журналирования (slog.Level)

	SetLevel(l) - обновить текущий уровень журналирования (slog.Level)

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

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

	Write(p []byte) (n int, err error) - метод для соответствия io.Writer

	NewLog(prefix string) *log.Logger - вернуть стандартный логгер с префиксом

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

Log(level slog.Level, msg string, args ...any)
Flood(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)
Crit(msg string, args ...any)
Fatal(msg string, args ...any)
Panic(msg string)

Logf(level slog.Level, format string, args ...any)
Floodf(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)
Critf(format string, args ...any)
Fatalf(format string, args ...any)

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

Вспомогательные функции работы с уровнями журналирования:

ParseLvl(lvl string) slog.Level - получить уровень из строки типа "debug"

ParseLevel(level slog.Level) string - преобразовать уровень к строке

Методы интерфейса Leveler:

Level() slog.Level - получить уровень журналирования (реализация интерфейса slog.Leveler)

Update(slog.Level) - обновить уровень журналирования

String() string - сформировать метку для журнала

ColorString() string - сформировать метку для журнала с ANSI/Escape подкраской

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
	AnsiBlackOnWhite     = "\033[30;107;1m" // Black on Bright White background
	AnsiBlueOnWhite      = "\033[34;47;1m"  // Blue on Bright White background
	AnsiWhiteOnMagenta   = "\033[37;45;1m"  // Bright White on Magenta background
	AnsiWhiteOnRed       = "\033[37;41;1m"  // White on Red background
)

ANSI modes

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

Level keys ANSI colors

View Source
const (
	AnsiTime   = AnsiYellow
	AnsiSource = AnsiMagenta
	AnsiKey    = AnsiCyan
	AnsiErrKey = AnsiRed
	AnsiErrVal = AnsiBrightRed
)

Log part colors

View Source
const (
	FILE      = "stdout" // log file path OR stdout/stderr ("" -> stdout)
	FILE_MODE = "0640"   // log file mode (if FILE is not stdout/stderr)
	LEVEL     = LvlInfo  // log level (flood/trace/debug/info/warn/error/critical/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, "15:04:05.999")
	SRC       = false    // log file name and line number
	SRC_LONG  = false    // log long file path (directory + file name)
	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

	// Pretty alignment time format in tinted handler (add zeros to end)
	TINT_ALIGN_TIME = true
)
View Source
const (
	LevelFlood    = slog.Level(-12) // FLOOD    (-12)
	LevelTrace    = slog.Level(-8)  // TRACE    (-8)
	LevelDebug    = slog.LevelDebug // DEBUG    (-4)
	LevelInfo     = slog.LevelInfo  // INFO     (0)
	LevelNotice   = slog.Level(2)   // NOTICE   (2)
	LevelWarn     = slog.LevelWarn  // WARN     (4)
	LevelError    = slog.LevelError // ERROR    (8)
	LevelCritical = slog.Level(12)  // CRITICAL (12)
	LevelFatal    = slog.Level(16)  // FATAL    (16)
	LevelPanic    = slog.Level(18)  // PANIC    (18)
	LevelSilent   = slog.Level(20)  // SILENT   (20)
)

Log levels delivered from slog.Level

View Source
const (
	LvlFlood    = "flood"
	LvlTrace    = "trace"
	LvlDebug    = "debug"
	LvlInfo     = "info"
	LvlNotice   = "notice"
	LvlWarn     = "warn"
	LvlError    = "error"
	LvlCritical = "critical"
	LvlFatal    = "fatal"
	LvlPanic    = "panic"
	LvlSilent   = "silent"
)

Log level as string for setup

View Source
const (
	LabelFlood    = "FLOOD"
	LabelTrace    = "TRACE"
	LabelDebug    = "DEBUG"
	LabelInfo     = "INFO"
	LabelNotice   = "NOTICE"
	LabelWarn     = "WARN"
	LabelError    = "ERROR"
	LabelCritical = "CRITICAL"
	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"

	// Time format for file names (no spaces, no ":", sorted by date/time)
	FILE_TIME_FORMAT = "2006-01-02_15.04.05"

	// Compromise time format (no spaces, no ":")
	COMPROMISE_TIME_FORMAT_DS = "2006-01-02_15.04.05.9"
	COMPROMISE_TIME_FORMAT    = "2006-01-02_15.04.05.999"
	COMPROMISE_TIME_FORMAT_US = "2006-01-02_15.04.05.999999"
	COMPROMISE_TIME_FORMAT_NS = "2006-01-02_15.04.05.999999999"

	// Digital clock
	CLOCK_TIME_FORMAT = "15:04"

	// 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 = 1 << 10 // 1K
View Source
const BUFFER_MAX_SIZE = 16 << 10 // 16K
View Source
const DEFAULT_LEVEL = LevelInfo
View Source
const DEFAULT_PREFIX = "LOG_"

Default prefix

View Source
const ERR_KEY = "err"
View Source
const NEW_LINE = '\n'

New line sequency

Variables

This section is empty.

Functions

func AddOpt

func AddOpt(opt *Opt, conf *Conf)

Add parsed command line options to logger config

func Crit added in v0.1.8

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

Crit logs at LevelCritical with default logger

func Critf added in v0.1.8

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

Critf logs at LevelCritical as standart logger with default logger

func Debug

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

Debug logs at LevelDebug with default logger

func Debugf

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

Debugf logs at LevelDebug as standart logger with default logger

func Env added in v0.2.5

func Env(conf *Conf, prefixOpt ...string)

Add settings from eviroment variables

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 logger

func Errorf

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

Errorf logs at LevelError as standart logger with default logger

func Fatal

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

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

func Fatalf

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

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

func Flood added in v0.1.5

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

Flood logs at LevelFlood with default logger

func Floodf added in v0.1.5

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

Floodf logs at LevelFlood as standart logger with default logger

func GetLevel

func GetLevel() slog.Level

Return current log level as int (slog.Level)

func GetLvl

func GetLvl() string

Return current log level as string

func Info

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

Info logs at LevelInfo with default logger

func Infof

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

Infof logs at LevelInfo as standart logger with default logger

func Int added in v1.0.0

func Int(key string, value int) slog.Attr

Integer return slog.Attr if key != "" and value != 0

func Log

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

Log logs at given level with default logger

func Logf

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

Logf logs at given level as standart logger with default logger

func NewLog

func NewLog(conf Conf) *log.Logger

Create new configured standart logger

func NewSlog

func NewSlog(conf Conf) *slog.Logger

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

func Notice

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

Notice logs at LevelNotice with default logger

func Noticef

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

Noticef logs at LevelNotice as standart logger with default logger

func Panic

func Panic(msg string)

Panic logs at LevelPanic with default logger and panic

func ParseLevel

func ParseLevel(level slog.Level) string

Parse Level (num to string: Level -> Lvl)

func ParseLvl

func ParseLvl(lvl string) slog.Level

Parse Lvl (string to num: Lvl -> Level)

func SetLevel added in v0.2.0

func SetLevel(level slog.Level)

Set current log level as int (slog.Level)

func SetLvl added in v0.2.0

func SetLvl(level string)

Set current log level as string

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 StringToBool added in v0.2.5

func StringToBool(s string) bool

String to bool converter

true:  true, True, yes, YES, on, 1, 2
false: false, FALSE, no, Off, 0, "Abra-Cadabra"

func TimeFormat added in v0.2.8

func TimeFormat(alias string) (format string, ok bool)

Return time format by alias

func Trace

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

Trace logs at LevelTrace with default logger

func Tracef

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

Tracef logs at LevelTrace as standart logger with default logger

func Warn

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

Warn logs at LevelWarn with default logger

func Warnf

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

Warnf logs at LevelWarn as standart logger with default logger

Types

type Buffer

type Buffer []byte

func NewBuffer

func NewBuffer() *Buffer

func (*Buffer) Free

func (b *Buffer) Free()

func (*Buffer) String added in v1.1.2

func (b *Buffer) String() string

func (*Buffer) Write

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

func (*Buffer) WriteByte

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

func (*Buffer) WriteString

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

func (*Buffer) WriteStringIf

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

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    string `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"`   // use timestamp in microseconds
	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 (directory + file name)
	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 (*Level) ColorString

func (lp *Level) ColorString() string

ColorString() returns a color label for the level

func (*Level) Level

func (lp *Level) Level() slog.Level

Level() returns log level (Level() - implements slog.Leveler interface)

func (*Level) String

func (lp *Level) String() string

String() returns a label for the level

func (*Level) Update added in v0.2.0

func (lp *Level) Update(level slog.Level)

Update log level

type Leveler added in v0.2.0

type Leveler interface {
	Level() slog.Level   // get log level as slog.Level (implements a slog.Leveler interface)
	Update(slog.Level)   // update log level
	String() string      // get log level as label
	ColorString() string // get log level as color label
}

xlog leveler interface (slog.Leveler + Update() + String()/ColorString() methods)

func NewSlogEx added in v0.2.0

func NewSlogEx(conf Conf) (*slog.Logger, Leveler)

Create new configured structured logger (default/text/JSON/Tinted handler) (return Leveler to may change log level later too)

type Logger added in v1.0.0

type Logger struct {
	Logger *slog.Logger
	Level  Leveler
}

Logger wrapper (logger + leveler)

func Current

func Current() *Logger

Return current Logger

func Default

func Default() *Logger

Create logger based on default slog.Logger

func New

func New(conf Conf) *Logger

Create new custom logger

func X

func X(logger *slog.Logger) *Logger

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

func (*Logger) Crit added in v1.0.0

func (x *Logger) Crit(msg string, args ...any)

Crit logs at LevelCritical

func (*Logger) Critf added in v1.0.0

func (x *Logger) Critf(format string, args ...any)

Critf logs at LevelCritical as standart logger

func (*Logger) Debug added in v1.0.0

func (x *Logger) Debug(msg string, args ...any)

Debug logs at LevelDebug

func (*Logger) Debugf added in v1.0.0

func (x *Logger) Debugf(format string, args ...any)

Debugf logs at LevelDebug as standart logger

func (*Logger) Error added in v1.0.0

func (x *Logger) Error(msg string, args ...any)

Error logs at LevelError

func (*Logger) Errorf added in v1.0.0

func (x *Logger) Errorf(format string, args ...any)

Errorf logs at LevelError as standart logger

func (*Logger) Fatal added in v1.0.0

func (x *Logger) Fatal(msg string, args ...any)

Fatal logs at LevelFatal and os.Exit(1)

func (*Logger) Fatalf added in v1.0.0

func (x *Logger) Fatalf(format string, args ...any)

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

func (*Logger) Flood added in v1.0.0

func (x *Logger) Flood(msg string, args ...any)

Flood logs at LevelFlood

func (*Logger) Floodf added in v1.0.0

func (x *Logger) Floodf(format string, args ...any)

Floodf logs at LevelFlood as standart logger

func (*Logger) GetLevel added in v1.0.0

func (x *Logger) GetLevel() slog.Level

Return log level as int (slog.Level)

func (*Logger) GetLvl added in v1.0.0

func (x *Logger) GetLvl() string

Return log level as string

func (*Logger) Info added in v1.0.0

func (x *Logger) Info(msg string, args ...any)

Info logs at LevelInfo

func (*Logger) Infof added in v1.0.0

func (x *Logger) Infof(format string, args ...any)

Infof logs at LevelInfo as standart logger

func (*Logger) Log added in v1.0.0

func (x *Logger) Log(level slog.Level, msg string, args ...any)

Log logs at given level

func (*Logger) Logf added in v1.0.0

func (x *Logger) Logf(level slog.Level, format string, args ...any)

Logf logs at given level as standart logger

func (*Logger) NewLog added in v1.0.0

func (x *Logger) NewLog(prefix string) *log.Logger

Return standart logger with prefix

func (*Logger) Notice added in v1.0.0

func (x *Logger) Notice(msg string, args ...any)

Notice logs at LevelNotice

func (*Logger) Noticef added in v1.0.0

func (x *Logger) Noticef(format string, args ...any)

Noticef logs at LevelNotice as standart logger

func (*Logger) Panic added in v1.0.0

func (x *Logger) Panic(msg string)

Panic logs at LevelPanic and panic

func (*Logger) SetDefault added in v1.0.0

func (x *Logger) SetDefault()

Set logger as default logger

func (*Logger) SetDefaultLogs added in v1.0.0

func (x *Logger) SetDefaultLogs()

Set logger as default xlog/log/slog loggers

func (*Logger) SetLevel added in v1.0.0

func (x *Logger) SetLevel(level slog.Level)

Set log level as int (slog.Level)

func (*Logger) SetLvl added in v1.0.0

func (x *Logger) SetLvl(level string)

Set log level as string

func (*Logger) Slog added in v1.0.0

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

Extract *slog.Logger (*xlog.Logger -> *slog.Logger)

func (*Logger) Trace added in v1.0.0

func (x *Logger) Trace(msg string, args ...any)

Trace logs at LevelTrace

func (*Logger) Tracef added in v1.0.0

func (x *Logger) Tracef(format string, args ...any)

Tracef logs at LevelTrace as standart logger

func (*Logger) Warn added in v1.0.0

func (x *Logger) Warn(msg string, args ...any)

Warn logs at LevelWarn

func (*Logger) Warnf added in v1.0.0

func (x *Logger) Warnf(format string, args ...any)

Warnf logs at LevelWarn as standart logger

func (*Logger) With added in v1.0.0

func (x *Logger) With(args ...any) *Logger

Create logger that includes the given attributes in each output

func (*Logger) WithAttrs added in v1.0.0

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

Create logger that includes the given attributes in each output

func (*Logger) WithGroup added in v1.0.0

func (x *Logger) WithGroup(name string) *Logger

Create logger that starts a group

func (*Logger) Write added in v1.0.0

func (x *Logger) Write(p []byte) (n int, err error)

Use logger as io.Writer: log to level Info

type Opt

type Opt struct {
	Level   string // -log <level>
	File    string // -lfile <file>
	SLog    bool   // -slog
	JLog    bool   // -jlog
	TLog    bool   // -tlog
	Src     bool   // -lsrc
	NoSrc   bool   // -lnosrc
	Pkg     bool   // -lpkg
	NoPkg   bool   // -lnopkg
	Time    bool   // -ltime
	NoTime  bool   // -lnotime
	TimeFmt string // -ltimefmt <fmt>
	NoLevel bool   // -lnolevel
	Color   bool   // -lcolor
	NoColor bool   // -lnocolor
}

Command line logger option structure

func NewOpt

func NewOpt() *Opt

Setup command line logger options Usage:

-log <level>       - log level (flood/trace/debug/info/notice/warm/error/critical)
-lfile <file>      - log file path or stdout/stderr
-slog              - use structured text logger (slog)
-jlog              - use structured JSON logger (slog)
-tlog              - use tinted (colorized) logger (tint)
-lsrc|-lnosrc      - force on/off log source file name and line number
-lpkg|-lnopkg      - force on/off log source directory/file name and line number
-ltime|-lnotime    - force on/off timestamp
-ltimefmt <format> - override log time format (e.g. 15:04:05.999 or TimeOnly)
-lnolevel          - disable log level tag (~level="INFO")
-lcolor|-lnocolor  - force enable/disable tinted colors

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) Format added in v1.1.0

func (h *TintHandler) Format(r slog.Record) string

Format record to byte array

func (*TintHandler) Handle

func (h *TintHandler) Handle(ctx 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 {
	// Minimum level to log (Default: slog.LevelInfo)
	Level slog.Leveler

	// Enable source code location
	AddSource bool

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

	// Off level keys
	NoLevel bool

	// Time format
	TimeFormat string

	// Disable color
	NoColor 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
}

type Xlogger added in v0.1.8

type Xlogger interface {
	// Create Logger that includes the given attributes in each output
	With(args ...any) *Logger

	// Create logger that includes the given attributes in each output
	WithAttrs(attrs []slog.Attr) *Logger

	// Create logger that starts a group
	WithGroup(name string) *Logger

	// Extract *slog.Logger (*xlog.Logger -> *slog.Logger)
	Slog() *slog.Logger

	// Set logger as default xlog logger
	SetDefault()

	// Set logger as default xlog/log/slog loggers
	SetDefaultLogs()

	// Return log level as int (slog.Level)
	GetLevel() slog.Level

	// Set log level as int (slog.Level)
	SetLevel(level slog.Level)

	// Return log level as string
	GetLvl() string

	// Set log level as string
	SetLvl(level string)

	// Use xlog as io.Writer: log to level Info
	Write(p []byte) (n int, err error)

	// Return standart logger with prefix
	NewLog(prefix string) *log.Logger

	// Log logs at given level
	Log(level slog.Level, msg string, args ...any)

	// Flood logs at LevelFlood
	Flood(msg string, args ...any)

	// Trace logs at LevelTrace
	Trace(msg string, args ...any)

	// Debug logs at LevelDebug
	Debug(msg string, args ...any)

	// Info logs at LevelInfo
	Info(msg string, args ...any)

	// Notice logs at LevelNotice
	Notice(msg string, args ...any)

	// Warn logs at LevelWarn
	Warn(msg string, args ...any)

	// Error logs at LevelError
	Error(msg string, args ...any)

	// Crit logs at LevelCritical
	Crit(msg string, args ...any)

	// Fatal logs at LevelFatal and os.Exit(1)
	Fatal(msg string, args ...any)

	// Panic logs at LevelPanic and panic
	Panic(msg string)

	// Logf logs at given level as standart logger
	Logf(level slog.Level, format string, args ...any)

	// Floodf logs at LevelFlood as standart logger
	Floodf(format string, args ...any)

	// Tracef logs at LevelTrace as standart logger
	Tracef(format string, args ...any)

	// Debugf logs at LevelDebug as standart logger
	Debugf(format string, args ...any)

	// Infof logs at LevelInfo as standart logger
	Infof(format string, args ...any)

	// Noticef logs at LevelNotice as standart logger
	Noticef(format string, args ...any)

	// Warnf logs at LevelWarn as standart logger
	Warnf(format string, args ...any)

	// Errorf logs at LevelError as standart logger
	Errorf(format string, args ...any)

	// Critf logs at LevelCritical as standart logger
	Critf(format string, args ...any)

	// Fatalf logs at LevelFatal as standart logger and os.Exit(1)
	Fatalf(format string, args ...any)
}

Logger interface

Jump to

Keyboard shortcuts

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