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
- func AddOpt(opt *Opt, conf *Conf)
- func Crit(msg string, args ...any)
- func Critf(format string, args ...any)
- func Debug(msg string, args ...any)
- func Debugf(format string, args ...any)
- func Env(conf *Conf, prefixOpt ...string)
- func Err(err error) slog.Attr
- func Error(msg string, args ...any)
- func Errorf(format string, args ...any)
- func Fatal(msg string, args ...any)
- func Fatalf(format string, args ...any)
- func Flood(msg string, args ...any)
- func Floodf(format string, args ...any)
- func GetLevel() slog.Level
- func GetLvl() string
- func Info(msg string, args ...any)
- func Infof(format string, args ...any)
- func Int(key string, value int) slog.Attr
- func Log(level slog.Level, msg string, args ...any)
- func Logf(level slog.Level, format string, args ...any)
- func NewLog(conf Conf) *log.Logger
- func NewSlog(conf Conf) *slog.Logger
- func Notice(msg string, args ...any)
- func Noticef(format string, args ...any)
- func Panic(msg string)
- func ParseLevel(level slog.Level) string
- func ParseLvl(lvl string) slog.Level
- func SetLevel(level slog.Level)
- func SetLvl(level string)
- func Setup(conf Conf)
- func SetupLog(logger *log.Logger, conf Conf)
- func Slog() *slog.Logger
- func String(key, value string) slog.Attr
- func StringToBool(s string) bool
- func TimeFormat(alias string) (format string, ok bool)
- func Trace(msg string, args ...any)
- func Tracef(format string, args ...any)
- func Warn(msg string, args ...any)
- func Warnf(format string, args ...any)
- type Buffer
- type Conf
- type Level
- type Leveler
- type Logger
- func (x *Logger) Crit(msg string, args ...any)
- func (x *Logger) Critf(format string, args ...any)
- func (x *Logger) Debug(msg string, args ...any)
- func (x *Logger) Debugf(format string, args ...any)
- func (x *Logger) Error(msg string, args ...any)
- func (x *Logger) Errorf(format string, args ...any)
- func (x *Logger) Fatal(msg string, args ...any)
- func (x *Logger) Fatalf(format string, args ...any)
- func (x *Logger) Flood(msg string, args ...any)
- func (x *Logger) Floodf(format string, args ...any)
- func (x *Logger) GetLevel() slog.Level
- func (x *Logger) GetLvl() string
- func (x *Logger) Info(msg string, args ...any)
- func (x *Logger) Infof(format string, args ...any)
- func (x *Logger) Log(level slog.Level, msg string, args ...any)
- func (x *Logger) Logf(level slog.Level, format string, args ...any)
- func (x *Logger) NewLog(prefix string) *log.Logger
- func (x *Logger) Notice(msg string, args ...any)
- func (x *Logger) Noticef(format string, args ...any)
- func (x *Logger) Panic(msg string)
- func (x *Logger) SetDefault()
- func (x *Logger) SetDefaultLogs()
- func (x *Logger) SetLevel(level slog.Level)
- func (x *Logger) SetLvl(level string)
- func (x *Logger) Slog() *slog.Logger
- func (x *Logger) Trace(msg string, args ...any)
- func (x *Logger) Tracef(format string, args ...any)
- func (x *Logger) Warn(msg string, args ...any)
- func (x *Logger) Warnf(format string, args ...any)
- func (x *Logger) With(args ...any) *Logger
- func (x *Logger) WithAttrs(attrs []slog.Attr) *Logger
- func (x *Logger) WithGroup(name string) *Logger
- func (x *Logger) Write(p []byte) (n int, err error)
- type Opt
- type TintHandler
- func (h *TintHandler) Enabled(_ context.Context, level slog.Level) bool
- func (h *TintHandler) Format(r slog.Record) string
- func (h *TintHandler) Handle(ctx context.Context, r slog.Record) error
- func (h *TintHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *TintHandler) WithGroup(name string) slog.Handler
- type TintOptions
- type Xlogger
Constants ¶
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
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
const ( AnsiTime = AnsiYellow AnsiSource = AnsiMagenta AnsiKey = AnsiCyan AnsiErrKey = AnsiRed AnsiErrVal = AnsiBrightRed )
Log part colors
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
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 )
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
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
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
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
const BUFFER_DEFAULT_CAP = 1 << 10 // 1K
const BUFFER_MAX_SIZE = 16 << 10 // 16K
const DEFAULT_LEVEL = LevelInfo
const DEFAULT_PREFIX = "LOG_"
Default prefix
const ERR_KEY = "err"
const NEW_LINE = '\n'
New line sequency
Variables ¶
This section is empty.
Functions ¶
func ParseLevel ¶
Parse Level (num to string: Level -> Lvl)
func StringToBool ¶ added in v0.2.5
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
Return time format by alias
Types ¶
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
type Level ¶
xlog level delivered from slog.Level, implements slog.Leveler interface
func (*Level) ColorString ¶
ColorString() returns a color label for the 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)
type Logger ¶ added in v1.0.0
Logger wrapper (logger + leveler)
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) With ¶ added in v1.0.0
Create logger that includes the given attributes in each output
func (*Logger) WithAttrs ¶ added in v1.0.0
Create logger that includes the given attributes in each output
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) Format ¶ added in v1.1.0
func (h *TintHandler) Format(r slog.Record) string
Format record to byte array
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