Documentation ¶
Overview ¶
Package slog A simple log library for 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.
Index ¶
- Constants
- Variables
- func AddHandler(h Handler)
- func AddHandlers(hs ...Handler)
- func AddProcessor(p Processor)
- func AddProcessors(ps ...Processor)
- func Configure(fn func(logger *SugaredLogger))
- func Debug(args ...interface{})
- func Debugf(format string, args ...interface{})
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func Exit(code int)
- func ExitHandlers() []func()
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func LevelName(l Level) string
- func Notice(args ...interface{})
- func Noticef(format string, args ...interface{})
- func PrependExitHandler(handler func())
- func Print(args ...interface{})
- func Printf(format string, args ...interface{})
- func Println(args ...interface{})
- func RegisterExitHandler(handler func())
- func Reset()
- func ResetExitHandlers(applyToStd bool)
- func SetExitFunc(fn func(code int))
- func SetFormatter(f Formatter)
- func Trace(args ...interface{})
- func Tracef(format string, args ...interface{})
- func Warn(args ...interface{})
- func Warnf(format string, args ...interface{})
- type FlushSyncWriter
- type Formattable
- type FormattableHandler
- type Formatter
- type FormatterFunc
- type Handler
- type JSONFormatter
- type Level
- type Logger
- func (logger *Logger) AddHandler(h Handler)
- func (logger *Logger) AddHandlers(hs ...Handler)
- func (logger *Logger) AddProcessor(p Processor)
- func (logger *Logger) AddProcessors(ps ...Processor)
- func (logger *Logger) Close()
- func (logger *Logger) Configure(fn func(logger *Logger)) *Logger
- func (logger *Logger) Debug(args ...interface{})
- func (logger *Logger) Debugf(format string, args ...interface{})
- func (logger *Logger) Error(args ...interface{})
- func (logger *Logger) Errorf(format string, args ...interface{})
- func (logger *Logger) Exit(code int)
- func (logger *Logger) ExitHandlers() []func()
- func (logger *Logger) Fatal(args ...interface{})
- func (logger *Logger) Fatalf(format string, args ...interface{})
- func (logger *Logger) FlushAll()
- func (logger *Logger) FlushDaemon()
- func (logger *Logger) Info(args ...interface{})
- func (logger *Logger) Infof(format string, args ...interface{})
- func (logger *Logger) Log(level Level, args ...interface{})
- func (logger *Logger) Logf(level Level, format string, args ...interface{})
- func (logger *Logger) Name() string
- func (logger *Logger) Notice(args ...interface{})
- func (logger *Logger) Noticef(format string, args ...interface{})
- func (logger *Logger) Panic(args ...interface{})
- func (logger *Logger) Panicf(format string, args ...interface{})
- func (logger *Logger) PrependExitHandler(handler func())
- func (logger *Logger) Print(args ...interface{})
- func (logger *Logger) Printf(format string, args ...interface{})
- func (logger *Logger) Println(args ...interface{})
- func (logger *Logger) PushHandler(h Handler)
- func (logger *Logger) PushProcessor(p Processor)
- func (logger *Logger) RegisterExitHandler(handler func())
- func (logger *Logger) Reset()
- func (logger *Logger) ResetExitHandlers()
- func (logger *Logger) ResetHandlers()
- func (logger *Logger) ResetProcessors()
- func (logger *Logger) SetHandlers(hs []Handler)
- func (logger *Logger) SetName(name string) *Logger
- func (logger *Logger) SetProcessors(ps []Processor)
- func (logger *Logger) Sync() error
- func (logger *Logger) Trace(args ...interface{})
- func (logger *Logger) Tracef(format string, args ...interface{})
- func (logger *Logger) VisitAll(fn func(handler Handler) error)
- func (logger *Logger) Warn(args ...interface{})
- func (logger *Logger) Warnf(format string, args ...interface{})
- func (logger *Logger) Warning(args ...interface{})
- func (logger *Logger) WithContext(ctx context.Context) *Record
- func (logger *Logger) WithData(data M) *Record
- func (logger *Logger) WithFields(fields M) *Record
- func (logger *Logger) WithTime(t time.Time) *Record
- 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 interface{}) *Record
- func (r *Record) AddFields(fields M) *Record
- func (r *Record) AddValue(key string, value interface{}) *Record
- func (r *Record) Copy() *Record
- func (r *Record) Debug(args ...interface{})
- func (r *Record) Debugf(format string, args ...interface{})
- func (r *Record) Error(args ...interface{})
- func (r *Record) Errorf(format string, args ...interface{})
- func (r *Record) Fatal(args ...interface{})
- func (r *Record) Fatalf(format string, args ...interface{})
- func (r *Record) Info(args ...interface{})
- func (r *Record) Infof(format string, args ...interface{})
- func (r *Record) Log(level Level, args ...interface{})
- func (r *Record) Logf(level Level, format string, args ...interface{})
- func (r *Record) NewBuffer() *bytes.Buffer
- func (r *Record) Notice(args ...interface{})
- func (r *Record) Noticef(format string, args ...interface{})
- func (r *Record) Panic(args ...interface{})
- func (r *Record) Panicf(format string, args ...interface{})
- func (r *Record) SetContext(ctx context.Context) *Record
- func (r *Record) SetData(data M) *Record
- func (r *Record) SetExtra(data M) *Record
- func (r *Record) SetFields(fields M) *Record
- func (r *Record) SetTime(t time.Time) *Record
- func (r *Record) Trace(args ...interface{})
- func (r *Record) Tracef(format string, args ...interface{})
- func (r *Record) WithContext(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 interface{}) *Record
- func (r *Record) WithFields(fields M) *Record
- func (r *Record) WithTime(t time.Time) *Record
- type StringMap
- type SugaredLogger
- type SyncWriter
- type TextFormatter
- type WriterHandler
Examples ¶
Constants ¶
const ( FieldKeyTime = "time" // FieldKeyDate = "date" FieldKeyData = "data" // NOTICE: you must set `Logger.ReportCaller=true` for "func", "file" FieldKeyFunc = "func" FieldKeyFile = "file" FieldKeyDatetime = "datetime" FieldKeyPosition = "position" FieldKeyTimestamp = "timestamp" FieldKeyLevel = "level" FieldKeyError = "error" FieldKeyExtra = "extra" // NOTICE: you must set `Logger.ReportCaller=true` for "caller" FieldKeyCaller = "caller" FieldKeyChannel = "channel" FieldKeyMessage = "message" )
const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"
const NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"
Variables ¶
var ( DefaultChannelName = "application" DefaultTimeFormat = "2006/01/02 15:04:05" // TimeFormatRFC3339 = time.RFC3339 FieldKeys = struct { Level string }{ Level: "level", } )
var ( // AllLevels exposing all logging levels AllLevels = []Level{ PanicLevel, FatalLevel, ErrorLevel, WarnLevel, NoticeLevel, InfoLevel, DebugLevel, TraceLevel, } // PrintLevel for use logger.Print / Printf / Println PrintLevel = NoticeLevel // LevelNames all level mapping name LevelNames = map[Level]string{ PanicLevel: "PANIC", FatalLevel: "FATAL", ErrorLevel: "ERROR", NoticeLevel: "NOTICE", WarnLevel: "WARNING", InfoLevel: "INFO", DebugLevel: "DEBUG", TraceLevel: "TRACE", } )
var ( // DefaultFields default log export fields 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{ FatalLevel: color.FgRed, ErrorLevel: color.FgMagenta, WarnLevel: color.FgYellow, NoticeLevel: color.OpBold, InfoLevel: color.FgGreen, DebugLevel: color.FgCyan, }
ColorTheme for format log to console
var (
// Define the key when adding errors using WithError.
ErrorKey = "error"
)
Functions ¶
func Exit ¶
func Exit(code int)
Exit runs all the logger exit handlers and then terminates the program using os.Exit(code)
func Noticef ¶
func Noticef(format string, args ...interface{})
Notice logs a message at level Notice
func PrependExitHandler ¶
func PrependExitHandler(handler func())
PrependExitHandler prepend register an exit-handler on global exitHandlers
func Print ¶ added in v0.0.3
func Print(args ...interface{})
Print logs a message at level PrintLevel
func Printf ¶ added in v0.0.3
func Printf(format string, args ...interface{})
Printf logs a message at level PrintLevel
func Println ¶ added in v0.0.3
func Println(args ...interface{})
Println logs a message at level PrintLevel
func RegisterExitHandler ¶
func RegisterExitHandler(handler func())
PrependExitHandler register an exit-handler on global exitHandlers
func ResetExitHandlers ¶
func ResetExitHandlers(applyToStd bool)
ResetExitHandlers reset all exitHandlers
Types ¶
type FlushSyncWriter ¶
FlushSyncWriter is the interface satisfied by logging destinations.
type Formattable ¶
type Formattable struct {
// contains filtered or unexported fields
}
Formattable definition
func (*Formattable) Formatter ¶
func (f *Formattable) Formatter() Formatter
Formatter get formatter. if not set, will return TextFormatter
func (*Formattable) SetFormatter ¶
func (f *Formattable) SetFormatter(formatter Formatter)
SetFormatter to handler
type FormattableHandler ¶
type FormattableHandler interface { // Formatter get the log formatter Formatter() Formatter // SetFormatter set the log formatter SetFormatter(Formatter) }
FormattableHandler interface
type FormatterFunc ¶
FormatterFunc wrapper definition
type Handler ¶
type Handler interface { // Close handler io.Closer // Flush logs to disk 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. 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 time.RFC3339 TimeFormat string }
JSONFormatter definition
func NewJSONFormatter ¶
func NewJSONFormatter(fn ...func(*JSONFormatter)) *JSONFormatter
NewJSONFormatter create new JSONFormatter
func (*JSONFormatter) Configure ¶
func (f *JSONFormatter) Configure(fn func(*JSONFormatter)) *JSONFormatter
Configure current formatter
type Level ¶
type Level uint32
Level type
const ( // PanicLevel level, 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
type Logger ¶
type Logger struct { ReportCaller bool LowerLevelName bool MaxCallerDepth int ExitFunc func(code int) // contains filtered or unexported fields }
Logger definition
func New ¶
func New() *Logger
New create an new logger
Example ¶
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") }
Output:
func NewWithConfig ¶
NewWithConfig create an new logger with config func
func NewWithHandlers ¶
NewWithHandlers create an new logger with handlers
func (*Logger) AddHandlers ¶
AddHandlers to the logger
func (*Logger) AddProcessor ¶
AddProcessor to the logger
func (*Logger) AddProcessors ¶
AddProcessors to the logger
func (*Logger) Debug ¶
func (logger *Logger) Debug(args ...interface{})
Debug logs a message at level Debug
func (*Logger) Error ¶
func (logger *Logger) Error(args ...interface{})
Error logs a message at level Error
func (*Logger) ExitHandlers ¶
func (logger *Logger) ExitHandlers() []func()
ExitHandlers get all exitHandlers of the logger
func (*Logger) Fatal ¶
func (logger *Logger) Fatal(args ...interface{})
Fatal logs a message at level Fatal
func (*Logger) FlushAll ¶
func (logger *Logger) FlushAll()
FlushAll flushes all the logs and attempts to "sync" their data to disk. logger.mu is held.
func (*Logger) FlushDaemon ¶
func (logger *Logger) FlushDaemon()
FlushDaemon run flush handle on daemon
Usage:
go slog.FlushDaemon()
func (*Logger) Info ¶
func (logger *Logger) Info(args ...interface{})
Info logs a message at level Info
func (*Logger) Notice ¶
func (logger *Logger) Notice(args ...interface{})
Notice logs a message at level Notice
func (*Logger) Panic ¶
func (logger *Logger) Panic(args ...interface{})
Panic logs a message at level Panic
func (*Logger) PrependExitHandler ¶
func (logger *Logger) PrependExitHandler(handler func())
PrependExitHandler prepend register an exit-handler on global exitHandlers
func (*Logger) Print ¶ added in v0.0.3
func (logger *Logger) Print(args ...interface{})
Print logs a message at level PrintLevel
func (*Logger) Println ¶ added in v0.0.3
func (logger *Logger) Println(args ...interface{})
Println logs a message at level PrintLevel
func (*Logger) PushHandler ¶
PushHandler to the logger. alias of AddHandler()
func (*Logger) PushProcessor ¶
PushProcessor to the logger. alias of AddProcessor()
func (*Logger) RegisterExitHandler ¶
func (logger *Logger) RegisterExitHandler(handler func())
PrependExitHandler register an exit-handler on global exitHandlers
func (*Logger) ResetExitHandlers ¶
func (logger *Logger) ResetExitHandlers()
ResetExitHandlers reset logger exitHandlers
func (*Logger) ResetProcessors ¶
func (logger *Logger) ResetProcessors()
ResetProcessors for the logger
func (*Logger) SetHandlers ¶
SetHandlers for the logger
func (*Logger) SetProcessors ¶
SetProcessors for the logger
func (*Logger) Trace ¶
func (logger *Logger) Trace(args ...interface{})
Trace logs a message at level Trace
func (*Logger) Warn ¶
func (logger *Logger) Warn(args ...interface{})
Warn logs a message at level Warn
func (*Logger) Warning ¶
func (logger *Logger) Warning(args ...interface{})
Warning logs a message at level Warn
func (*Logger) WithContext ¶
WithContext new record with context.Context
func (*Logger) WithFields ¶
SetFields new record with 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 records
type ProcessableHandler ¶
type ProcessableHandler interface { // AddProcessor add an processor AddProcessor(Processor) // SetProcessor set the log processor 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
type ProcessorFunc ¶
type ProcessorFunc func(record *Record)
ProcessorFunc wrapper definition
var MemoryUsage ProcessorFunc = func(record *Record) { stat := new(runtime.MemStats) runtime.ReadMemStats(stat) record.Extra["memoryUsage"] = stat.Alloc }
MemoryUsage Get memory usage.
type Record ¶
type Record struct { Time time.Time Level Level // level name from Level LevelName string // Channel log channel name. eg: "order", "goods", "user" Channel string Message string // Ctx context.Context Ctx context.Context // Buffer Can use Buffer on formatter Buffer *bytes.Buffer // Fields custom fields. Contains all the fields set by the user. Fields M // log data Data M // Extra log extra data Extra M // Caller information Caller *runtime.Frame // contains filtered or unexported fields }
Record a log record definition
func (*Record) Debug ¶
func (r *Record) Debug(args ...interface{})
Debug logs a message at level Debug
func (*Record) Error ¶
func (r *Record) Error(args ...interface{})
Error logs a message at level Error
func (*Record) Fatal ¶
func (r *Record) Fatal(args ...interface{})
Fatal logs a message at level Fatal
func (*Record) Notice ¶
func (r *Record) Notice(args ...interface{})
Notice logs a message at level Notice
func (*Record) Panic ¶
func (r *Record) Panic(args ...interface{})
Panic logs a message at level Panic
func (*Record) SetContext ¶
SetContext on record
func (*Record) Trace ¶
func (r *Record) Trace(args ...interface{})
Trace logs a message at level Trace
func (*Record) WithContext ¶
WithContext on record
func (*Record) WithFields ¶
WithField with new fields to record
type SugaredLogger ¶
type SugaredLogger struct { *Logger // Formatter log message formatter. default use TextFormatter Formatter Formatter // Output output writer Output io.Writer // Level for log handling. // Greater than or equal to this level will be recorded Level Level }
SugaredLogger definition. Is a fast and usable Logger, which already contains the default formatting and handling capabilities
func NewJSONSugared ¶
func NewJSONSugared(out io.Writer, level Level) *SugaredLogger
NewJSONSugared create new SugaredLogger with JSONFormatter
func NewSugaredLogger ¶
func NewSugaredLogger(output io.Writer, level Level) *SugaredLogger
NewSugaredLogger create new SugaredLogger
func (*SugaredLogger) Configure ¶
func (sl *SugaredLogger) Configure(fn func(sl *SugaredLogger)) *SugaredLogger
Configure current logger
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 SyncWriter ¶
SyncWriter is the interface satisfied by logging destinations.
type TextFormatter ¶
type TextFormatter struct { // Template text template for render output log messages Template string // TimeFormat the time format layout. default is time.RFC3339 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 `fmt.Sprint()` EncodeFunc func(v interface{}) string // contains filtered or unexported fields }
TextFormatter definition
func NewTextFormatter ¶
func NewTextFormatter(template ...string) *TextFormatter
NewTextFormatter create new TextFormatter
func (*TextFormatter) FieldMap ¶
func (f *TextFormatter) FieldMap() StringMap
FieldMap get export field map
type WriterHandler ¶
WriterHandler is the interface satisfied by logging destinations.