Documentation ¶
Overview ¶
Package slog Lightweight, extensible, configurable logging library written in Go.
Source code and other details for the project are available at GitHub:
https://github.com/gookit/slog
Quick usage:
package main import ( "github.com/gookit/slog" ) func main() { slog.Info("info log message") slog.Warn("warning log message") slog.Infof("info log %s", "message") slog.Debugf("debug %s", "message") }
More usage please see README.
Example (ConfigSlog) ¶
package main import ( "github.com/gookit/slog" ) func main() { slog.Configure(func(logger *slog.SugaredLogger) { f := logger.Formatter.(*slog.TextFormatter) f.EnableColor = true }) slog.Trace("this is a simple log message") slog.Debug("this is a simple log message") slog.Info("this is a simple log message") slog.Notice("this is a simple log message") slog.Warn("this is a simple log message") slog.Error("this is a simple log message") slog.Fatal("this is a simple log message") }
Output:
Example (QuickStart) ¶
package main import ( "github.com/gookit/slog" ) func main() { slog.Info("info log message") slog.Warn("warning log message") slog.Infof("info log %s", "message") slog.Debugf("debug %s", "message") }
Output:
Example (UseJSONFormat) ¶
package main import ( "github.com/gookit/slog" ) func main() { // use JSON formatter slog.SetFormatter(slog.NewJSONFormatter()) slog.Info("info log message") slog.Warn("warning log message") slog.WithData(slog.M{ "key0": 134, "key1": "abc", }).Infof("info log %s", "message") r := slog.WithFields(slog.M{ "category": "service", "IP": "127.0.0.1", }) r.Infof("info %s", "message") r.Debugf("debug %s", "message") }
Output:
Index ¶
- Constants
- Variables
- func AddHandler(h Handler)
- func AddHandlers(hs ...Handler)
- func AddProcessor(p Processor)
- func AddProcessors(ps ...Processor)
- func Close() error
- func Configure(fn func(l *SugaredLogger))
- func Debug(args ...any)
- func Debugf(format string, args ...any)
- func EncodeToString(v any) string
- func Error(args ...any)
- func ErrorT(err error)
- func Errorf(format string, args ...any)
- func Exit(code int)
- func ExitHandlers() []func()
- func Fatal(args ...any)
- func FatalErr(err error)
- func Fatalf(format string, args ...any)
- func Flush() error
- func FlushDaemon(onStops ...func())
- func FlushTimeout(timeout time.Duration)
- func Info(args ...any)
- func Infof(format string, args ...any)
- func LevelName(l Level) string
- func MustClose()
- func MustFlush()
- func Notice(args ...any)
- func Noticef(format string, args ...any)
- func Panic(args ...any)
- func PanicErr(err error)
- func Panicf(format string, args ...any)
- func PrependExitHandler(handler func())
- func Print(args ...any)
- func Printf(format string, args ...any)
- func Println(args ...any)
- func PushHandler(h Handler)
- func PushHandlers(hs ...Handler)
- func RegisterExitHandler(handler func())
- func Reset()
- func ResetExitHandlers(applyToStd bool)
- func SetExitFunc(fn func(code int))
- func SetFormatter(f Formatter)
- func SetLogLevel(l Level)
- func StopDaemon()
- func Trace(args ...any)
- func Tracef(format string, args ...any)
- func Warn(args ...any)
- func Warnf(format string, args ...any)
- type CallerFormatFn
- type ClockFn
- type Formattable
- type FormattableHandler
- type FormattableTrait
- type Formatter
- type FormatterFunc
- type FormatterWrapper
- type Handler
- type JSONFormatter
- type Level
- type LevelFormattable
- type LevelFormatting
- type LevelHandling
- type LevelMode
- type LevelWithFormatter
- type Levels
- type LevelsWithFormatter
- type Logger
- func (l *Logger) AddHandler(h Handler)
- func (l *Logger) AddHandlers(hs ...Handler)
- func (l *Logger) AddProcessor(p Processor)
- func (l *Logger) AddProcessors(ps ...Processor)
- func (l *Logger) Close() error
- func (l *Logger) Config(fns ...LoggerFn) *Logger
- func (l *Logger) Configure(fn LoggerFn) *Logger
- func (l *Logger) Debug(args ...any)
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) DoNothingOnPanicFatal()
- func (l *Logger) Error(args ...any)
- func (l *Logger) ErrorT(err error)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) Exit(code int)
- func (l *Logger) ExitHandlers() []func()
- func (l *Logger) Fatal(args ...any)
- func (l *Logger) Fatalf(format string, args ...any)
- func (l *Logger) Fatalln(args ...any)
- func (l *Logger) Flush() error
- func (l *Logger) FlushAll() error
- func (l *Logger) FlushDaemon(onStops ...func())
- func (l *Logger) FlushTimeout(timeout time.Duration)
- func (l *Logger) HandlersNum() int
- func (l *Logger) Info(args ...any)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) LastErr() error
- func (l *Logger) Log(level Level, args ...any)
- func (l *Logger) Logf(level Level, format string, args ...any)
- func (l *Logger) MustClose()
- func (l *Logger) MustFlush()
- func (l *Logger) Name() string
- func (l *Logger) Notice(args ...any)
- func (l *Logger) Noticef(format string, args ...any)
- func (l *Logger) Panic(args ...any)
- func (l *Logger) Panicf(format string, args ...any)
- func (l *Logger) Panicln(args ...any)
- func (l *Logger) PrependExitHandler(handler func())
- func (l *Logger) Print(args ...any)
- func (l *Logger) Printf(format string, args ...any)
- func (l *Logger) Println(args ...any)
- func (l *Logger) PushHandler(h Handler)
- func (l *Logger) PushHandlers(hs ...Handler)
- func (l *Logger) PushProcessor(p Processor)
- func (l *Logger) Record() *Record
- func (l *Logger) RegisterExitHandler(handler func())
- func (l *Logger) Reset()
- func (l *Logger) ResetExitHandlers()
- func (l *Logger) ResetHandlers()
- func (l *Logger) ResetProcessors()
- func (l *Logger) Reused() *Record
- func (l *Logger) SetHandlers(hs []Handler)
- func (l *Logger) SetName(name string)
- func (l *Logger) SetProcessors(ps []Processor)
- func (l *Logger) StopDaemon()
- func (l *Logger) Sync() error
- func (l *Logger) Trace(args ...any)
- func (l *Logger) Tracef(format string, args ...any)
- func (l *Logger) VisitAll(fn func(handler Handler) error) error
- func (l *Logger) Warn(args ...any)
- func (l *Logger) Warnf(format string, args ...any)
- func (l *Logger) Warning(args ...any)
- func (l *Logger) WithContext(ctx context.Context) *Record
- func (l *Logger) WithCtx(ctx context.Context) *Record
- func (l *Logger) WithData(data M) *Record
- func (l *Logger) WithExtra(ext M) *Record
- func (l *Logger) WithField(name string, value any) *Record
- func (l *Logger) WithFields(fields M) *Record
- func (l *Logger) WithTime(t time.Time) *Record
- func (l *Logger) WithValue(key string, value any) *Record
- type LoggerFn
- type M
- type Processable
- type ProcessableHandler
- type Processor
- type ProcessorFunc
- type Record
- func (r *Record) AddData(data M) *Record
- func (r *Record) AddExtra(data M) *Record
- func (r *Record) AddField(name string, val any) *Record
- func (r *Record) AddFields(fields M) *Record
- func (r *Record) AddValue(key string, value any) *Record
- func (r *Record) Copy() *Record
- func (r *Record) Debug(args ...any)
- func (r *Record) Debugf(format string, args ...any)
- func (r *Record) Error(args ...any)
- func (r *Record) Errorf(format string, args ...any)
- func (r *Record) Fatal(args ...any)
- func (r *Record) Fatalf(format string, args ...any)
- func (r *Record) Fatalln(args ...any)
- func (r *Record) Field(key string) any
- func (r *Record) GoString() string
- func (r *Record) Info(args ...any)
- func (r *Record) Infof(format string, args ...any)
- func (r *Record) Init(lowerLevelName bool)
- func (r *Record) LevelName() string
- func (r *Record) Log(level Level, args ...any)
- func (r *Record) Logf(level Level, format string, args ...any)
- func (r *Record) Notice(args ...any)
- func (r *Record) Noticef(format string, args ...any)
- func (r *Record) Panic(args ...any)
- func (r *Record) Panicf(format string, args ...any)
- func (r *Record) Panicln(args ...any)
- func (r *Record) Print(args ...any)
- func (r *Record) Printf(format string, args ...any)
- func (r *Record) Println(args ...any)
- func (r *Record) Release()
- func (r *Record) Reused() *Record
- func (r *Record) SetContext(ctx context.Context) *Record
- func (r *Record) SetCtx(ctx context.Context) *Record
- func (r *Record) SetData(data M) *Record
- func (r *Record) SetExtra(data M) *Record
- func (r *Record) SetExtraValue(k string, v any)
- func (r *Record) SetFields(fields M) *Record
- func (r *Record) SetTime(t time.Time) *Record
- func (r *Record) Trace(args ...any)
- func (r *Record) Tracef(format string, args ...any)
- func (r *Record) Value(key string) any
- func (r *Record) Warn(args ...any)
- func (r *Record) Warnf(format string, args ...any)
- func (r *Record) WithContext(ctx context.Context) *Record
- func (r *Record) WithCtx(ctx context.Context) *Record
- func (r *Record) WithData(data M) *Record
- func (r *Record) WithError(err error) *Record
- func (r *Record) WithField(name string, val any) *Record
- func (r *Record) WithFields(fields M) *Record
- func (r *Record) WithTime(t time.Time) *Record
- type SLogger
- type StringMap
- type SugaredLogger
- func NewJSONSugared(out io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
- func NewStd(fns ...SugaredLoggerFn) *SugaredLogger
- func NewStdLogger(fns ...SugaredLoggerFn) *SugaredLogger
- func NewSugared(out io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
- func NewSugaredLogger(output io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
- func Std() *SugaredLogger
- func (sl *SugaredLogger) Close() error
- func (sl *SugaredLogger) Config(fns ...SugaredLoggerFn) *SugaredLogger
- func (sl *SugaredLogger) Flush() error
- func (sl *SugaredLogger) FlushAll() error
- func (sl *SugaredLogger) Handle(record *Record) error
- func (sl *SugaredLogger) IsHandling(level Level) bool
- func (sl *SugaredLogger) Reset()
- type SugaredLoggerFn
- type TextFormatter
- func (f *TextFormatter) Configure(fn TextFormatterFn) *TextFormatter
- func (f *TextFormatter) Fields() []string
- func (f *TextFormatter) Format(r *Record) ([]byte, error)
- func (f *TextFormatter) SetTemplate(fmtTpl string)
- func (f *TextFormatter) Template() string
- func (f *TextFormatter) WithEnableColor(enable bool) *TextFormatter
- func (f *TextFormatter) WithOptions(fns ...TextFormatterFn) *TextFormatter
- type TextFormatterFn
Examples ¶
Constants ¶
const ( // CallerFlagFnlFcn report short func name with filename and with line. // eg: "logger_test.go:48,TestLogger_ReportCaller" CallerFlagFnlFcn uint8 = iota // CallerFlagFull full func name with filename and with line. // eg: "github.com/gookit/slog_test.TestLogger_ReportCaller(),logger_test.go:48" CallerFlagFull // CallerFlagFunc full package with func name. // eg: "github.com/gookit/slog_test.TestLogger_ReportCaller" CallerFlagFunc // CallerFlagFcLine full package with func name and with line. // eg: "github.com/gookit/slog_test.TestLogger_ReportCaller:48" CallerFlagFcLine // CallerFlagPkg report full package name. // eg: "github.com/gookit/slog_test" CallerFlagPkg // CallerFlagPkgFnl report full package name + filename + line. // eg: "github.com/gookit/slog_test,logger_test.go:48" CallerFlagPkgFnl // CallerFlagFpLine report full filepath with line. // eg: "/work/go/gookit/slog/logger_test.go:48" CallerFlagFpLine // CallerFlagFnLine report filename with line. // eg: "logger_test.go:48" CallerFlagFnLine // CallerFlagFcName only report func name. // eg: "TestLogger_ReportCaller" CallerFlagFcName )
NOTICE: you must set `Logger.ReportCaller=true` for reporting caller. then config the Logger.CallerFlag by follow flags.
const ( DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n" NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n" )
there are built in text log template
Variables ¶
var ( // FieldKeyData define the key name for Record.Data FieldKeyData = "data" // FieldKeyTime key name FieldKeyTime = "time" // FieldKeyDate key name FieldKeyDate = "date" // FieldKeyDatetime key name FieldKeyDatetime = "datetime" // FieldKeyTimestamp key name FieldKeyTimestamp = "timestamp" // FieldKeyCaller the field key name for report caller. // // For caller style please see CallerFlagFull, CallerFlagFunc and more. // // NOTICE: you must set `Logger.ReportCaller=true` for reporting caller FieldKeyCaller = "caller" // FieldKeyLevel name FieldKeyLevel = "level" // FieldKeyError Define the key when adding errors using WithError. FieldKeyError = "error" // FieldKeyExtra key name FieldKeyExtra = "extra" // FieldKeyChannel name FieldKeyChannel = "channel" // FieldKeyMessage name FieldKeyMessage = "message" )
var ( // DefaultChannelName for log record DefaultChannelName = "application" // DefaultTimeFormat define DefaultTimeFormat = "2006/01/02T15:04:05.000" // DoNothingOnExit handle func. use for testing. DoNothingOnExit = func(code int) {} // DoNothingOnPanic handle func. use for testing. DoNothingOnPanic = func(v any) {} // DefaultPanicFn handle func DefaultPanicFn = func(v any) { panic(v) } // DefaultClockFn create func DefaultClockFn = ClockFn(func() time.Time { return time.Now() }) )
var ( // PrintLevel for use logger.Print / Printf / Println PrintLevel = InfoLevel // AllLevels exposing all logging levels AllLevels = Levels{ PanicLevel, FatalLevel, ErrorLevel, WarnLevel, NoticeLevel, InfoLevel, DebugLevel, TraceLevel, } // DangerLevels define the commonly danger log levels DangerLevels = Levels{PanicLevel, FatalLevel, ErrorLevel, WarnLevel} // NormalLevels define the commonly normal log levels NormalLevels = Levels{InfoLevel, NoticeLevel, DebugLevel, TraceLevel} // LevelNames all level mapping name LevelNames = map[Level]string{ PanicLevel: "PANIC", FatalLevel: "FATAL", ErrorLevel: "ERROR", WarnLevel: "WARN", NoticeLevel: "NOTICE", InfoLevel: "INFO", DebugLevel: "DEBUG", TraceLevel: "TRACE", } )
var ( // DefaultFields default log export fields for json formatter. DefaultFields = []string{ FieldKeyDatetime, FieldKeyChannel, FieldKeyLevel, FieldKeyCaller, FieldKeyMessage, FieldKeyData, FieldKeyExtra, } // NoTimeFields log export fields without time NoTimeFields = []string{ FieldKeyChannel, FieldKeyLevel, FieldKeyMessage, FieldKeyData, FieldKeyExtra, } )
var ColorTheme = map[Level]color.Color{ PanicLevel: color.FgRed, FatalLevel: color.FgRed, ErrorLevel: color.FgMagenta, WarnLevel: color.FgYellow, NoticeLevel: color.OpBold, InfoLevel: color.FgGreen, DebugLevel: color.FgCyan, }
ColorTheme for format log to console
Functions ¶
func Close ¶ added in v0.5.4
func Close() error
Close logger, flush and close all handlers.
IMPORTANT: please call Close() before app exit.
func EncodeToString ¶ added in v0.2.0
EncodeToString data to string
func Exit ¶
func Exit(code int)
Exit runs all exit handlers and then terminates the program using os.Exit(code)
func FatalErr ¶ added in v0.3.1
func FatalErr(err error)
FatalErr logs a message at level Fatal on err is not nil
func FlushDaemon ¶ added in v0.1.1
func FlushDaemon(onStops ...func())
FlushDaemon run flush handle on daemon.
Usage please see slog_test.ExampleFlushDaemon()
Example ¶
package main import ( "fmt" "sync" "time" "github.com/gookit/slog" ) func main() { wg := sync.WaitGroup{} wg.Add(1) go slog.FlushDaemon(func() { fmt.Println("flush daemon stopped") slog.MustClose() wg.Done() }) go func() { // mock app running time.Sleep(time.Second * 2) // stop daemon fmt.Println("stop flush daemon") slog.StopDaemon() }() // wait for stop wg.Wait() }
Output:
func FlushTimeout ¶ added in v0.1.1
FlushTimeout flush logs with timeout.
func MustClose ¶ added in v0.5.4
func MustClose()
MustClose logger, flush and close all handlers.
IMPORTANT: please call Close() before app exit.
func PanicErr ¶ added in v0.3.1
func PanicErr(err error)
PanicErr logs a message at level Panic on err is not nil
func PrependExitHandler ¶
func PrependExitHandler(handler func())
PrependExitHandler prepend register an exit-handler on global exitHandlers
func RegisterExitHandler ¶
func RegisterExitHandler(handler func())
RegisterExitHandler register an exit-handler on global exitHandlers
func ResetExitHandlers ¶
func ResetExitHandlers(applyToStd bool)
ResetExitHandlers reset all exitHandlers
func SetLogLevel ¶ added in v0.0.6
func SetLogLevel(l Level)
SetLogLevel max level for the std logger
Types ¶
type CallerFormatFn ¶ added in v0.5.3
CallerFormatFn caller format func
type Formattable ¶
type Formattable interface { // Formatter get the log formatter Formatter() Formatter // SetFormatter set the log formatter SetFormatter(Formatter) }
Formattable interface
type FormattableHandler ¶
type FormattableHandler interface { Handler Formattable }
FormattableHandler interface
type FormattableTrait ¶ added in v0.5.0
type FormattableTrait = FormatterWrapper
FormattableTrait alias of FormatterWrapper
type Formatter ¶
type Formatter interface { // Format you can format record and write result to record.Buffer Format(record *Record) ([]byte, error) }
Formatter interface
type FormatterFunc ¶
FormatterFunc wrapper definition
type FormatterWrapper ¶ added in v0.5.3
type FormatterWrapper struct {
// contains filtered or unexported fields
}
FormatterWrapper use for format log record. default use the TextFormatter
func (*FormatterWrapper) Format ¶ added in v0.5.3
func (f *FormatterWrapper) Format(record *Record) ([]byte, error)
Format log record to bytes
func (*FormatterWrapper) Formatter ¶ added in v0.5.3
func (f *FormatterWrapper) Formatter() Formatter
Formatter get formatter. if not set, will return TextFormatter
func (*FormatterWrapper) SetFormatter ¶ added in v0.5.3
func (f *FormatterWrapper) SetFormatter(formatter Formatter)
SetFormatter to handler
type Handler ¶
type Handler interface { // Closer Close handler. // You should first call Flush() on close logic. // Refer the FileHandler.Close() handle io.Closer // Flush and sync logs to disk file. Flush() error // IsHandling Checks whether the given record will be handled by this handler. IsHandling(level Level) bool // Handle a log record. // // All records may be passed to this method, and the handler should discard // those that it does not want to handle. Handle(*Record) error }
Handler interface definition
type JSONFormatter ¶
type JSONFormatter struct { // Fields exported log fields. default is DefaultFields Fields []string // Aliases for output fields. you can change export field name. // // item: `"field" : "output name"` // eg: {"message": "msg"} export field will display "msg" Aliases StringMap // PrettyPrint will indent all json logs PrettyPrint bool // TimeFormat the time format layout. default is DefaultTimeFormat TimeFormat string // CallerFormatFunc the caller format layout. default is defined by CallerFlag CallerFormatFunc CallerFormatFn }
JSONFormatter definition
func AsJSONFormatter ¶ added in v0.5.0
func AsJSONFormatter(f Formatter) *JSONFormatter
AsJSONFormatter util func
func NewJSONFormatter ¶
func NewJSONFormatter(fn ...func(f *JSONFormatter)) *JSONFormatter
NewJSONFormatter create new JSONFormatter
func (*JSONFormatter) AddField ¶ added in v0.3.0
func (f *JSONFormatter) AddField(name string) *JSONFormatter
AddField for export
func (*JSONFormatter) Configure ¶
func (f *JSONFormatter) Configure(fn func(*JSONFormatter)) *JSONFormatter
Configure current formatter
type Level ¶
type Level uint32
Level type
const ( // PanicLevel level, the highest level of severity. will call panic() if the logging level <= PanicLevel. PanicLevel Level = 100 // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the // logging level <= FatalLevel. FatalLevel Level = 200 // ErrorLevel level. Runtime errors. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel Level = 300 // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel Level = 400 // NoticeLevel level Uncommon events NoticeLevel Level = 500 // InfoLevel level. Examples: User logs in, SQL logs. InfoLevel Level = 600 // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel Level = 700 // TraceLevel level. Designates finer-grained informational events than the Debug. TraceLevel Level = 800 )
These are the different logging levels. You can set the logging level to log handler
func LevelByName ¶ added in v0.3.0
LevelByName convert name to level
func (Level) ShouldHandling ¶ added in v0.1.3
ShouldHandling compare level, if current level <= l, it will be record.
type LevelFormattable ¶ added in v0.3.0
type LevelFormattable interface { Formattable IsHandling(level Level) bool }
LevelFormattable support limit log levels and provide formatter
type LevelFormatting ¶ added in v0.5.3
type LevelFormatting struct { LevelHandling FormatterWrapper }
LevelFormatting wrap level handling and log formatter
func NewLevelsFormatting ¶ added in v0.5.3
func NewLevelsFormatting(levels []Level) *LevelFormatting
NewLevelsFormatting create new instance with levels
func NewMaxLevelFormatting ¶ added in v0.5.3
func NewMaxLevelFormatting(maxLevel Level) *LevelFormatting
NewMaxLevelFormatting create new instance with max level
type LevelHandling ¶ added in v0.5.3
type LevelHandling struct {
// contains filtered or unexported fields
}
LevelHandling struct definition
func (*LevelHandling) IsHandling ¶ added in v0.5.3
func (h *LevelHandling) IsHandling(level Level) bool
IsHandling Check if the current level can be handling
func (*LevelHandling) SetLimitLevels ¶ added in v0.5.3
func (h *LevelHandling) SetLimitLevels(levels []Level)
SetLimitLevels set limit levels for log message
func (*LevelHandling) SetMaxLevel ¶ added in v0.5.3
func (h *LevelHandling) SetMaxLevel(maxLv Level)
SetMaxLevel set max level for log message
type LevelWithFormatter ¶ added in v0.3.0
type LevelWithFormatter struct { FormattableTrait // Level max for log message. if current level <= Level will log message Level Level }
LevelWithFormatter struct definition
- support set log formatter - only support set max log level
func NewLvFormatter ¶ added in v0.3.0
func NewLvFormatter(maxLv Level) *LevelWithFormatter
NewLvFormatter create new LevelWithFormatter instance
func (*LevelWithFormatter) IsHandling ¶ added in v0.3.0
func (h *LevelWithFormatter) IsHandling(level Level) bool
IsHandling Check if the current level can be handling
func (*LevelWithFormatter) SetMaxLevel ¶ added in v0.5.3
func (h *LevelWithFormatter) SetMaxLevel(maxLv Level)
SetMaxLevel set max level for log message
type LevelsWithFormatter ¶ added in v0.3.0
type LevelsWithFormatter struct { FormattableTrait // Levels for log message Levels []Level }
LevelsWithFormatter struct definition
- support set log formatter - support setting multi log levels
func NewLvsFormatter ¶ added in v0.3.0
func NewLvsFormatter(levels []Level) *LevelsWithFormatter
NewLvsFormatter create new instance
func (*LevelsWithFormatter) IsHandling ¶ added in v0.3.0
func (h *LevelsWithFormatter) IsHandling(level Level) bool
IsHandling Check if the current level can be handling
func (*LevelsWithFormatter) SetLimitLevels ¶ added in v0.5.3
func (h *LevelsWithFormatter) SetLimitLevels(levels []Level)
SetLimitLevels set limit levels for log message
type Logger ¶
type Logger struct { // ChannelName log channel name, default is DefaultChannelName ChannelName string // FlushInterval flush interval time. default is defaultFlushInterval=30s FlushInterval time.Duration // LowerLevelName use lower level name LowerLevelName bool // ReportCaller on write log record ReportCaller bool CallerSkip int CallerFlag uint8 // BackupArgs backup log input args to Record.Args BackupArgs bool // TimeClock custom time clock, timezone TimeClock ClockFn // custom exit, panic handler. ExitFunc func(code int) PanicFunc func(v any) // contains filtered or unexported fields }
Logger log dispatcher definition.
The logger implements the `github.com/gookit/gsr.Logger`
func New ¶
New create a new logger
Example ¶
package main import ( "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func main() { mylog := slog.New() levels := slog.AllLevels mylog.AddHandler(handler.MustFileHandler("app.log", handler.WithLogLevels(levels))) mylog.Info("info log message") mylog.Warn("warning log message") mylog.Infof("info log %s", "message") }
Output:
func NewWithConfig ¶
NewWithConfig create a new logger with config func
func NewWithHandlers ¶
NewWithHandlers create a new logger with handlers
func NewWithName ¶
NewWithName create a new logger with name
func (*Logger) AddProcessors ¶
AddProcessors to the logger. alias of AddProcessor()
func (*Logger) Close ¶
Close the logger, will flush all logs and close all handlers
IMPORTANT:
if enable async/buffer mode, please call the Close() before exit.
func (*Logger) DoNothingOnPanicFatal ¶ added in v0.3.0
func (l *Logger) DoNothingOnPanicFatal()
DoNothingOnPanicFatal do nothing on panic or fatal level. useful on testing.
func (*Logger) ExitHandlers ¶
func (l *Logger) ExitHandlers() []func()
ExitHandlers get all exitHandlers of the logger
func (*Logger) Flush ¶ added in v0.1.0
Flush flushes all the logs and attempts to "sync" their data to disk. l.mu is held.
func (*Logger) FlushAll ¶
FlushAll flushes all the logs and attempts to "sync" their data to disk.
alias of the Flush()
func (*Logger) FlushDaemon ¶
func (l *Logger) FlushDaemon(onStops ...func())
FlushDaemon run flush handle on daemon
Usage please refer to the FlushDaemon() on package.
func (*Logger) FlushTimeout ¶ added in v0.1.1
FlushTimeout flush logs on limit time.
refer from glog package
func (*Logger) HandlersNum ¶ added in v0.5.4
HandlersNum returns the number of handlers
func (*Logger) MustClose ¶ added in v0.5.4
func (l *Logger) MustClose()
MustClose close logger. will panic on error
func (*Logger) MustFlush ¶ added in v0.3.0
func (l *Logger) MustFlush()
MustFlush flush logs. will panic on error
func (*Logger) PrependExitHandler ¶
func (l *Logger) PrependExitHandler(handler func())
PrependExitHandler prepend register an exit-handler on global exitHandlers
func (*Logger) PushHandler ¶
PushHandler to the l. alias of AddHandler()
func (*Logger) PushHandlers ¶ added in v0.1.3
PushHandlers to the logger
func (*Logger) PushProcessor ¶
PushProcessor to the logger, alias of AddProcessor()
func (*Logger) Record ¶ added in v0.3.0
Record return a new record with logger, will release after write log.
func (*Logger) RegisterExitHandler ¶
func (l *Logger) RegisterExitHandler(handler func())
RegisterExitHandler register an exit-handler on global exitHandlers
func (*Logger) Reset ¶
func (l *Logger) Reset()
Reset the logger. will reset: handlers, processors, closed=false
func (*Logger) ResetExitHandlers ¶
func (l *Logger) ResetExitHandlers()
ResetExitHandlers reset logger exitHandlers
func (*Logger) Reused ¶ added in v0.5.5
Reused return a new record with logger, but it can be reused. if you want to release the record, please call the Record.Release() after write log.
Usage:
r := logger.Reused() defer r.Release() // can write log multiple times r.Info("some message1") r.Warn("some message1")
func (*Logger) SetProcessors ¶
SetProcessors for the logger
func (*Logger) StopDaemon ¶ added in v0.5.3
func (l *Logger) StopDaemon()
StopDaemon stop flush daemon
func (*Logger) WithContext ¶
WithContext new record with context.Context
func (*Logger) WithField ¶ added in v0.3.0
WithField new record with field
TIP: add field need config Formatter template fields.
func (*Logger) WithFields ¶
WithFields new record with fields
TIP: add field need config Formatter template fields.
type Processable ¶
type Processable struct {
// contains filtered or unexported fields
}
Processable definition
func (*Processable) AddProcessor ¶
func (p *Processable) AddProcessor(processor Processor)
AddProcessor to the handler
func (*Processable) ProcessRecord ¶
func (p *Processable) ProcessRecord(r *Record)
ProcessRecord process record
type ProcessableHandler ¶
type ProcessableHandler interface { // AddProcessor add a processor AddProcessor(Processor) // ProcessRecord handle a record ProcessRecord(record *Record) }
ProcessableHandler interface
type Processor ¶
type Processor interface { // Process record Process(record *Record) }
Processor interface definition
func AddUniqueID ¶ added in v0.0.3
AddUniqueID to record
func AppendCtxKeys ¶ added in v0.5.1
AppendCtxKeys append context keys to record.Fields
type ProcessorFunc ¶
type ProcessorFunc func(record *Record)
ProcessorFunc wrapper definition
var MemoryUsage ProcessorFunc = func(record *Record) { stat := new(runtime.MemStats) runtime.ReadMemStats(stat) record.SetExtraValue("memoryUsage", stat.Alloc) }
MemoryUsage get memory usage.
type Record ¶
type Record struct { // Time for record log, if is empty will use now. // // TIP: Will be emptied after each use (write) Time time.Time // Level log level for record Level Level // Channel log channel name. eg: "order", "goods", "user" Channel string Message string // Ctx context.Context Ctx context.Context // Fields custom fields data. // Contains all the fields set by the user. Fields M // Data log context data Data M // Extra log extra data Extra M // Caller information Caller *runtime.Frame // CallerFlag value. default is equals to Logger.CallerFlag CallerFlag uint8 // CallerSkip value. default is equals to Logger.CallerSkip CallerSkip int // EnableStack enable stack info, default is false. TODO EnableStack bool // log input args backups, from log() and logf(). its dont use in formatter. Fmt string Args []any // contains filtered or unexported fields }
Record a log record definition
func WithContext ¶ added in v0.5.2
WithContext new record with context
func WithField ¶ added in v0.5.2
WithField new record with field.
TIP: add field need config Formatter template fields.
func WithFields ¶
WithFields new record with fields
TIP: add field need config Formatter template fields.
func (*Record) Println ¶ added in v0.2.0
Println logs a message at level Print, will not append \n. alias of Print
func (*Record) Release ¶ added in v0.5.5
func (r *Record) Release()
Release manual release record to pool
func (*Record) Reused ¶ added in v0.5.5
Reused set record is reused, will not be released on after write.
func (*Record) SetContext ¶
SetContext on record
func (*Record) SetExtraValue ¶ added in v0.2.0
SetExtraValue on record
func (*Record) WithContext ¶
WithContext on record
func (*Record) WithField ¶
WithField with a new field to record
Note: add field need config Formatter template fields.
func (*Record) WithFields ¶
WithFields with new fields to record
Note: add field need config Formatter template fields.
type SLogger ¶ added in v0.3.0
type SLogger interface { gsr.Logger Log(level Level, v ...any) Logf(level Level, format string, v ...any) }
SLogger interface
type SugaredLogger ¶
type SugaredLogger struct { *Logger // Formatter log message formatter. default use TextFormatter Formatter Formatter // Output writer Output io.Writer // Level for log handling. if log record level <= Level, it will be record. Level Level }
SugaredLogger Is a fast and usable Logger, which already contains the default formatting and handling capabilities
func NewJSONSugared ¶
func NewJSONSugared(out io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
NewJSONSugared create new SugaredLogger with JSONFormatter
func NewStd ¶ added in v0.5.2
func NewStd(fns ...SugaredLoggerFn) *SugaredLogger
NewStd logger instance, alias of NewStdLogger()
func NewStdLogger ¶ added in v0.2.0
func NewStdLogger(fns ...SugaredLoggerFn) *SugaredLogger
NewStdLogger instance
func NewSugared ¶ added in v0.5.2
func NewSugared(out io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
NewSugared create new SugaredLogger. alias of NewSugaredLogger()
func NewSugaredLogger ¶
func NewSugaredLogger(output io.Writer, level Level, fns ...SugaredLoggerFn) *SugaredLogger
NewSugaredLogger create new SugaredLogger
func (*SugaredLogger) Close ¶
func (sl *SugaredLogger) Close() error
Close all log handlers, will flush and close all handlers.
IMPORTANT:
if enable async/buffer mode, please call the Close() before exit.
func (*SugaredLogger) Config ¶ added in v0.3.0
func (sl *SugaredLogger) Config(fns ...SugaredLoggerFn) *SugaredLogger
Config current logger
func (*SugaredLogger) Flush ¶
func (sl *SugaredLogger) Flush() error
Flush all logs. alias of the FlushAll()
func (*SugaredLogger) FlushAll ¶ added in v0.1.1
func (sl *SugaredLogger) FlushAll() error
FlushAll all logs
func (*SugaredLogger) Handle ¶
func (sl *SugaredLogger) Handle(record *Record) error
Handle log record
func (*SugaredLogger) IsHandling ¶
func (sl *SugaredLogger) IsHandling(level Level) bool
IsHandling Check if the current level can be handling
type SugaredLoggerFn ¶ added in v0.4.0
type SugaredLoggerFn func(sl *SugaredLogger)
SugaredLoggerFn func type.
type TextFormatter ¶
type TextFormatter struct { // TimeFormat the time format layout. default is DefaultTimeFormat TimeFormat string // Enable color on print log to terminal EnableColor bool // ColorTheme setting on render color on terminal ColorTheme map[Level]color.Color // FullDisplay Whether to display when record.Data, record.Extra, etc. are empty FullDisplay bool // EncodeFunc data encode for Record.Data, Record.Extra, etc. // // Default is encode by EncodeToString() EncodeFunc func(v any) string // CallerFormatFunc the caller format layout. default is defined by CallerFlag CallerFormatFunc CallerFormatFn // contains filtered or unexported fields }
TextFormatter definition
func AsTextFormatter ¶ added in v0.5.0
func AsTextFormatter(f Formatter) *TextFormatter
AsTextFormatter util func
func NewTextFormatter ¶
func NewTextFormatter(template ...string) *TextFormatter
NewTextFormatter create new TextFormatter
func TextFormatterWith ¶ added in v0.5.6
func TextFormatterWith(fns ...TextFormatterFn) *TextFormatter
TextFormatterWith create new TextFormatter with options
func (*TextFormatter) Configure ¶ added in v0.5.3
func (f *TextFormatter) Configure(fn TextFormatterFn) *TextFormatter
Configure the formatter
func (*TextFormatter) Fields ¶ added in v0.2.0
func (f *TextFormatter) Fields() []string
Fields get export field list
func (*TextFormatter) Format ¶
func (f *TextFormatter) Format(r *Record) ([]byte, error)
Format a log record
func (*TextFormatter) SetTemplate ¶ added in v0.0.7
func (f *TextFormatter) SetTemplate(fmtTpl string)
SetTemplate set the log format template and update field-map
func (*TextFormatter) Template ¶ added in v0.0.2
func (f *TextFormatter) Template() string
Template get
func (*TextFormatter) WithEnableColor ¶ added in v0.5.3
func (f *TextFormatter) WithEnableColor(enable bool) *TextFormatter
WithEnableColor enable color on print log to terminal
func (*TextFormatter) WithOptions ¶ added in v0.5.6
func (f *TextFormatter) WithOptions(fns ...TextFormatterFn) *TextFormatter
WithOptions func on the formatter
type TextFormatterFn ¶ added in v0.5.6
type TextFormatterFn func(*TextFormatter)
TextFormatterFn definition
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package bufwrite provides buffered io.Writer with sync and close methods.
|
Package bufwrite provides buffered io.Writer with sync and close methods. |
Package handler provide useful common log handlers.
|
Package handler provide useful common log handlers. |
Package rotatefile provides simple file rotation, compression and cleanup.
|
Package rotatefile provides simple file rotation, compression and cleanup. |