Slog
📑 Lightweight, configurable, extensible logging library written in Go. Support multi level, multi outputs and built-in multi file logger, buffers, clean, rotate-file handling.一个易于使用的,轻量级、可配置、可扩展的日志库。支持多个级别,输出到多文件;内置文件日志处理、自动切割、清理、压缩等增强功能
Install / Use
/learn @gookit/SlogREADME
slog
📑 Lightweight, structured, extensible, configurable logging library written in Golang.
Output in console:

Features
- Simple, directly available without configuration
- Support common log level processing.
- eg:
tracedebuginfonoticewarnerrorfatalpanic
- eg:
- Support any extension of
HandlerFormatteras needed - Supports adding multiple
Handlerlog processing at the same time, outputting logs to different places - Support to custom log message
Formatter- Built-in
jsontexttwo log record formattingFormatter
- Built-in
- Support to custom build log messages
Handler- The built-in
handler.Confighandler.Buildercan easily and quickly build the desired log handler
- The built-in
- Has built-in common log write handler program
consoleoutput logs to the console, supports color outputwriteroutput logs to the specifiedio.Writerfileoutput log to the specified file, optionally enablebufferto buffer writessimpleoutput log to the specified file, write directly to the file without bufferingrotate_fileoutputs logs to the specified file, and supports splitting files by time and size, andbufferbuffered writing is enabled by default- See ./handler folder for more built-in implementations
- Benchmark performance test please see Benchmarks
Output logs to file
- Support enabling
bufferfor log writing - Support splitting log files by
timeandsize - Support configuration to compress log files via
gzip - Support clean old log files by
BackupNumBackupTime
rotatefile subpackage
- The
rotatefilesubpackage is a stand-alone tool library with file splitting, cleaning, and compressing backups rotatefile.Writercan also be directly wrapped and used in other logging libraries. For example:log,glog,zap, etc.rotatefile.FilesClearis an independent file cleaning backup tool, which can be used in other places (such as other program log cleaning such as PHP)- For more usage, please see rotatefile
Use slog in GORM
Please see https://github.com/gookit/slog/issues/127#issuecomment-2827745713
中文说明
中文说明请阅读 README.zh-CN
GoDoc
Install
go get github.com/gookit/slog
Quick Start
slog is very simple to use and can be used without any configuration
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:
[2020/07/16 12:19:33] [application] [INFO] [main.go:7] info log message
[2020/07/16 12:19:33] [application] [WARNING] [main.go:8] warning log message
[2020/07/16 12:19:33] [application] [INFO] [main.go:9] info log message
[2020/07/16 12:19:33] [application] [DEBUG] [main.go:10] debug message
Console Color
You can enable color on output logs to console. This is default
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:

Change log output style
Above is the Formatter setting that changed the default logger.
You can also create your own logger and append
ConsoleHandlerto support printing logs to the console:
h := handler.NewConsoleHandler(slog.AllLevels)
l := slog.NewWithHandlers(h)
l.Trace("this is a simple log message")
l.Debug("this is a simple log message")
Change the default logger log output style:
h.Formatter().(*slog.TextFormatter).SetTemplate(slog.NamedTemplate)
Output:

Note:
slog.TextFormatteruses a template string to format the output log, so the new field output needs to adjust the template at the same time.
Use JSON Format
slog also has a built-in Formatter for JSON format. If not specified, the default is to use TextFormatter to format log records.
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:
{"channel":"application","data":{},"datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info log message"}
{"channel":"application","data":{},"datetime":"2020/07/16 13:23:33","extra":{},"level":"WARNING","message":"warning log message"}
{"channel":"application","data":{"key0":134,"key1":"abc"},"datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info log message"}
{"IP":"127.0.0.1","category":"service","channel":"application","datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info message"}
{"IP":"127.0.0.1","category":"service","channel":"application","datetime":"2020/07/16 13:23:33","extra":{},"level":"DEBUG","message":"debug message"}
Introduction
Logger- log dispatcher. One logger can register multipleHandler,ProcessorRecord- log records, each log is aRecordinstance.Processor- enables extended processing of log records. It is called before the logRecordis processed by theHandler.- You can use it to perform additional operations on
Record, such as: adding fields, adding extended information, etc.
- You can use it to perform additional operations on
Handler- log handler, each log will be processed byHandler.Handle().- Here you can send logs to console, file, remote server, etc.
Formatter- logging data formatting process.- Usually set in
Handler, it can be used to format log records, convert records into text, JSON, etc.,Handlerthen writes the formatted data to the specified place. Formatteris not required. You can do without it and handle logging directly inHandler.Handle().
- Usually set in
Simple structure of log scheduler:
Processors
Logger --{
Handlers --|- Handler0 With Formatter0
|- Handler1 With Formatter1
|- Handler2 (can also without Formatter)
|- ... more
Note: Be sure to remember to add
Handler,Processorto the logger instance and log records will be processed byHandler.
Processor
Processor interface:
// Processor interface definition
type Processor interface {
// Process record
Process(record *Record)
}
// ProcessorFunc definition
type ProcessorFunc func(record *Record)
// Process record
func (fn ProcessorFunc) Process(record *Record) {
fn(record)
}
You can use it to perform additional operations on the Record before the log
Recordreaches theHandlerfor processing, such as: adding fields, adding extended information, etc.
Add processor to logger:
slog.AddProcessor(slog.AddHostname())
// or
l := slog.New()
l.AddProcessor(slog.AddHostname())
The built-in processor slog.AddHostname is used here as an example, which can add a new field hostname on each log record.
slog.AddProcessor(slog.AddHostname())
slog.Info("message")
Output, including new fields "hostname":"InhereMac":
{"channel":"application","level":"INFO","datetime":"2020/07/17 12:01:35","hostname":"InhereMac","data":{},"extra":{},"message":"message"}
Handler
Handler interface:
You can customize any
Handleryou want, just implement theslog.Handlerinterface.
// Handler interface definition
type Handler interface {
io.Closer
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
}
Formatter
Formatter interface:
// Formatter interface
type Formatter interface {
Format(record *Record) ([]byte, error)
}
Function wrapper type:
// FormatterFunc wrapper definition
type FormatterFunc func(r *Record) ([]byte, error)
// Format a log record
func (fn FormatterFunc) Format(r *Record) ([]byte, error) {
return fn(r)
}
JSON formatter
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 ind
