slog

package module
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2024 License: MIT Imports: 20 Imported by: 169

README

slog

GitHub go.mod Go version GoDoc Go Report Card Unit-Tests GitHub tag (latest SemVer) Coverage Status

📑 Lightweight, extensible, configurable logging library written in Golang.

Output in console:

console-log-all-level

Features

  • Simple, directly available without configuration
  • Support common log level processing.
    • eg: trace debug info notice warn error fatal panic
  • Support any extension of Handler Formatter as needed
  • Supports adding multiple Handler log processing at the same time, outputting logs to different places
  • Support to custom log message Formatter
    • Built-in json text two log record formatting Formatter
  • Support to custom build log messages Handler
    • The built-in handler.Config handler.Builder can easily and quickly build the desired log handler
  • Has built-in common log write handler program
    • console output logs to the console, supports color output
    • writer output logs to the specified io.Writer
    • file output log to the specified file, optionally enable buffer to buffer writes
    • simple output log to the specified file, write directly to the file without buffering
    • rotate_file outputs logs to the specified file, and supports splitting files by time and size, and buffer buffered 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 buffer for log writing
  • Support splitting log files by time and size
  • Support configuration to compress log files via gzip
  • Support clean old log files by BackupNum BackupTime
rotatefile subpackage
  • The rotatefile subpackage is a stand-alone tool library with file splitting, cleaning, and compressing backups
  • rotatefile.Writer can also be directly wrapped and used in other logging libraries. For example: log, glog, zap, etc.
  • rotatefile.FilesClear is 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

中文说明

中文说明请阅读 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 ConsoleHandler to 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.TextFormatter uses 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 multiple Handler, Processor
  • Record - log records, each log is a Record instance.
  • Processor - enables extended processing of log records. It is called before the log Record is processed by the Handler.
    • You can use it to perform additional operations on Record, such as: adding fields, adding extended information, etc.
  • Handler - log handler, each log will be processed by Handler.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., Handler then writes the formatted data to the specified place.
    • Formatter is not required. You can do without it and handle logging directly in Handler.Handle().

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, Processor to the logger instance and log records will be processed by Handler.

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 Record reaches the Handler for 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 Handler you want, just implement the slog.Handler interface.

// 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 indent all json logs
	PrettyPrint bool
	// TimeFormat the time format layout. default is time.RFC3339
	TimeFormat string
}

Text formatter

Default templates:

const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"
const NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"

Change template:

myTemplate := "[{{datetime}}] [{{level}}] {{message}}"

f := slog.NewTextFormatter()
f.SetTemplate(myTemplate)

Custom logger

Custom Processor and Formatter are relatively simple, just implement a corresponding method.

Create new logger

slog.Info, slog.Warn and other methods use the default logger and output logs to the console by default.

You can create a brand-new instance of slog.Logger:

Method 1

l := slog.New()
// add handlers ...
h1 := handler.NewConsoleHandler(slog.AllLevels)
l.AddHandlers(h1)

Method 2

l := slog.NewWithName("myLogger")
// add handlers ...
h1 := handler.NewConsoleHandler(slog.AllLevels)
l.AddHandlers(h1)

Method 3

package main

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
)

func main() {
	l := slog.NewWithHandlers(handler.NewConsoleHandler(slog.AllLevels))
	l.Info("message")
}
Create custom Handler

You only need to implement the slog.Handler interface to create a custom Handler.

You can quickly assemble your own Handler through the built-in handler.LevelsWithFormatter handler.LevelWithFormatter and other fragments of slog.

Examples:

Use handler.LevelsWithFormatter, only need to implement Close, Flush, Handle methods

type MyHandler struct {
	handler.LevelsWithFormatter
    Output io.Writer
}

func (h *MyHandler) Handle(r *slog.Record) error {
	// you can write log message to file or send to remote.
}

func (h *MyHandler) Flush() error {}
func (h *MyHandler) Close() error {}

Add Handler to the logger to use:

// add to default logger
slog.AddHander(&MyHandler{})

// or, add to custom logger:
l := slog.New()
l.AddHander(&MyHandler{})

Use the built-in handlers

./handler package has built-in common log handlers, which can basically meet most scenarios.

// Output logs to console, allow render color.
func NewConsoleHandler(levels []slog.Level) *ConsoleHandler
// Send logs to email
func NewEmailHandler(from EmailOption, toAddresses []string) *EmailHandler
// Send logs to syslog
func NewSysLogHandler(priority syslog.Priority, tag string) (*SysLogHandler, error)
// A simple handler implementation that outputs logs to a given io.Writer
func NewSimpleHandler(out io.Writer, level slog.Level) *SimpleHandler

Output log to file:

// Output log to the specified file, without buffering by default
func NewFileHandler(logfile string, fns ...ConfigFn) (h *SyncCloseHandler, err error)
// Output logs to the specified file in JSON format, without buffering by default
func JSONFileHandler(logfile string, fns ...ConfigFn) (*SyncCloseHandler, error)
// Buffered output log to specified file
func NewBuffFileHandler(logfile string, buffSize int, fns ...ConfigFn) (*SyncCloseHandler, error)

TIP: NewFileHandler JSONFileHandler can also enable write buffering by passing in fns handler.WithBuffSize(buffSize)

Output log to file and rotate automatically:

// Automatic rotating according to file size
func NewSizeRotateFile(logfile string, maxSize int, fns ...ConfigFn) (*SyncCloseHandler, error)
// Automatic rotating according to time
func NewTimeRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)
// It supports configuration to rotate according to size and time. 
// The default setting file size is 20M, and the default automatic splitting time is 1 hour (EveryHour).
func NewRotateFileHandler(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)

TIP: By passing in fns ...ConfigFn, more options can be set, such as log file retention time, log write buffer size, etc. For detailed settings, see the handler.Config structure

Logs to file

Output log to the specified file, buffer buffered writing is not enabled by default. Buffering can also be enabled by passing in a parameter.

package mypkg

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
)

func main() {
	defer slog.MustClose()

	// DangerLevels contains: slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel
	h1 := handler.MustFileHandler("/tmp/error.log", handler.WithLogLevels(slog.DangerLevels))
	// custom log format
	// f := h1.Formatter().(*slog.TextFormatter)
	f := slog.AsTextFormatter(h1.Formatter())
	f.SetTemplate("your template format\n")

	// NormalLevels contains: slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel
	h2 := handler.MustFileHandler("/tmp/info.log", handler.WithLogLevels(slog.NormalLevels))

	// register handlers
	slog.PushHandler(h1)
	slog.PushHandler(h2)

	// add logs
	slog.Info("info message text")
	slog.Error("error message text")
}

Note: If write buffering buffer is enabled, be sure to call logger.Close() at the end of the program to flush the contents of the buffer to the file.

Log to file with automatic rotating

slog/handler also has a built-in output log to a specified file, and supports splitting files by time and size at the same time. By default, buffer buffered writing is enabled

func Example_rotateFileHandler() {
	h1 := handler.MustRotateFile("/tmp/error.log", handler.EveryHour, handler.WithLogLevels(slog.DangerLevels))
	h2 := handler.MustRotateFile("/tmp/info.log", handler.EveryHour, handler.WithLogLevels(slog.NormalLevels))

	slog.PushHandler(h1)
	slog.PushHandler(h2)

	// add logs
	slog.Info("info message")
	slog.Error("error message")
}

Example of file name sliced by time:

time-rotate-file.log
time-rotate-file.log.20201229_155753
time-rotate-file.log.20201229_155754

Example of a filename cut by size, in the format filename.log.HIS_000N. For example:

size-rotate-file.log
size-rotate-file.log.122915_0001
size-rotate-file.log.122915_0002
Use rotatefile on another logger

rotatefile.Writer can also be used with other logging packages, such as: log, glog, etc.

For example, using rotatefile on golang log:

package main

import (
  "log"

  "github.com/gookit/slog/rotatefile"
)

func main() {
	logFile := "testdata/go_logger.log"
	writer, err := rotatefile.NewConfig(logFile).Create()
	if err != nil {
		panic(err) 
	}

	log.SetOutput(writer)
	log.Println("log message")
}
Quickly create a Handler based on config

This is config struct for create a Handler:

// Config struct
type Config struct {
	// Logfile for write logs
	Logfile string `json:"logfile" yaml:"logfile"`
	// LevelMode for filter log record. default LevelModeList
	LevelMode uint8 `json:"level_mode" yaml:"level_mode"`
	// Level value. use on LevelMode = LevelModeValue
	Level slog.Level `json:"level" yaml:"level"`
	// Levels for log record
	Levels []slog.Level `json:"levels" yaml:"levels"`
	// UseJSON for format logs
	UseJSON bool `json:"use_json" yaml:"use_json"`
	// BuffMode type name. allow: line, bite
	BuffMode string `json:"buff_mode" yaml:"buff_mode"`
	// BuffSize for enable buffer, unit is bytes. set 0 to disable buffer
	BuffSize int `json:"buff_size" yaml:"buff_size"`
	// RotateTime for rotate file, unit is seconds.
	RotateTime rotatefile.RotateTime `json:"rotate_time" yaml:"rotate_time"`
	// MaxSize on rotate file by size, unit is bytes.
	MaxSize uint64 `json:"max_size" yaml:"max_size"`
	// Compress determines if the rotated log files should be compressed using gzip.
	// The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"`
	// BackupNum max number for keep old files.
	// 0 is not limit, default is 20.
	BackupNum uint `json:"backup_num" yaml:"backup_num"`
	// BackupTime max time for keep old files. unit is hours
	// 0 is not limit, default is a week.
	BackupTime uint `json:"backup_time" yaml:"backup_time"`
	// RenameFunc build filename for rotate file
	RenameFunc func(filepath string, rotateNum uint) string
}

Examples:

	testFile := "testdata/error.log"

	h := handler.NewEmptyConfig(
			handler.WithLogfile(testFile),
			handler.WithBuffSize(1024*8),
			handler.WithLogLevels(slog.DangerLevels),
			handler.WithBuffMode(handler.BuffModeBite),
		).
		CreateHandler()

	l := slog.NewWithHandlers(h)

About BuffMode

Config.BuffMode The name of the BuffMode type to use. Allow: line, bite

  • BuffModeBite: Buffer by bytes, when the number of bytes in the buffer reaches the specified size, write the contents of the buffer to the file
  • BuffModeLine: Buffer by line, when the buffer size is reached, always ensure that a complete line of log content is written to the file (to avoid log content being truncated)
Use Builder to quickly create Handler

Use handler.Builder to easily and quickly create Handler instances.

	testFile := "testdata/info.log"

	h := handler.NewBuilder().
		WithLogfile(testFile).
		WithLogLevels(slog.NormalLevels).
		WithBuffSize(1024*8).
		WithBuffMode(handler.BuffModeBite).
		WithRotateTime(rotatefile.Every30Min).
		WithCompress(true).
		Build()

	l := slog.NewWithHandlers(h)

Extension packages

Package bufwrite:

  • bufwrite.BufIOWriter additionally implements Sync(), Close() methods by wrapping go's bufio.Writer, which is convenient to use
  • bufwrite.LineWriter refer to the implementation of bufio.Writer in go, which can support flushing the buffer by line, which is more useful for writing log files

Package rotatefile:

  • rotatefile.Writer implements automatic cutting of log files according to size and specified time, and also supports automatic cleaning of log files
    • handler/rotate_file is to use it to cut the log file
Use rotatefile on other log package

Of course, the rotatefile.Writer can be use on other log package, such as: log, glog and more.

Examples, use rotatefile on golang log:

package main

import (
  "log"

  "github.com/gookit/slog/rotatefile"
)

func main() {
	logFile := "testdata/another_logger.log"
	writer, err := rotatefile.NewConfig(logFile).Create()
	if err != nil {
		panic(err) 
	}

	log.SetOutput(writer)
	log.Println("log message")
}

Testing and benchmark

Unit tests

run unit tests:

go test ./...
Benchmarks

Benchmark code at _example/bench_loglibs_test.go

make test-bench

Benchmarks for slog and other log packages:

Note: test and record ad 2023.04.13

goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz
BenchmarkZapNegative
BenchmarkZapNegative-4                   8381674              1429 ns/op             216 B/op          3 allocs/op
BenchmarkZapSugarNegative
BenchmarkZapSugarNegative-4              8655980              1383 ns/op             104 B/op          4 allocs/op
BenchmarkZeroLogNegative
BenchmarkZeroLogNegative-4              14173719               849.8 ns/op             0 B/op          0 allocs/op
BenchmarkPhusLogNegative
BenchmarkPhusLogNegative-4              27456256               451.2 ns/op             0 B/op          0 allocs/op
BenchmarkLogrusNegative
BenchmarkLogrusNegative-4                2550771              4784 ns/op             608 B/op         17 allocs/op
BenchmarkGookitSlogNegative
>>>> BenchmarkGookitSlogNegative-4       8798220              1375 ns/op             120 B/op          3 allocs/op
BenchmarkZapPositive
BenchmarkZapPositive-4                  10302483              1167 ns/op             192 B/op          1 allocs/op
BenchmarkZapSugarPositive
BenchmarkZapSugarPositive-4              3833311              3154 ns/op             344 B/op          7 allocs/op
BenchmarkZeroLogPositive
BenchmarkZeroLogPositive-4              14120524               846.7 ns/op             0 B/op          0 allocs/op
BenchmarkPhusLogPositive
BenchmarkPhusLogPositive-4              27152686               434.9 ns/op             0 B/op          0 allocs/op
BenchmarkLogrusPositive
BenchmarkLogrusPositive-4                2601892              4691 ns/op             608 B/op         17 allocs/op
BenchmarkGookitSlogPositive
>>>> BenchmarkGookitSlogPositive-4            8997104              1340 ns/op             120 B/op          3 allocs/op
PASS
ok      command-line-arguments  167.095s

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli Build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, extensible, configurable logging library written in Go
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

Acknowledgment

The projects is heavily inspired by follow packages:

LICENSE

MIT

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

Examples

Constants

View Source
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.

View Source
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

View Source
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"
)
View Source
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()
	})
)
View Source
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",
	}
)
View Source
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,
	}
)
View Source
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 AddHandler

func AddHandler(h Handler)

AddHandler to the std logger

func AddHandlers

func AddHandlers(hs ...Handler)

AddHandlers to the std logger

func AddProcessor

func AddProcessor(p Processor)

AddProcessor to the logger

func AddProcessors

func AddProcessors(ps ...Processor)

AddProcessors to the logger

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 Configure

func Configure(fn func(l *SugaredLogger))

Configure the std logger

func Debug

func Debug(args ...any)

Debug logs a message at level Debug

func Debugf

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

Debugf logs a message at level Debug

func EncodeToString added in v0.2.0

func EncodeToString(v any) string

EncodeToString data to string

func Error

func Error(args ...any)

Error logs a message at level Error

func ErrorT added in v0.1.5

func ErrorT(err error)

ErrorT logs a error type at level Error

func Errorf

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

Errorf logs a message at level Error

func Exit

func Exit(code int)

Exit runs all exit handlers and then terminates the program using os.Exit(code)

func ExitHandlers

func ExitHandlers() []func()

ExitHandlers get all global exitHandlers

func Fatal

func Fatal(args ...any)

Fatal logs a message at level Fatal

func FatalErr added in v0.3.1

func FatalErr(err error)

FatalErr logs a message at level Fatal on err is not nil

func Fatalf

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

Fatalf logs a message at level Fatal

func Flush added in v0.0.7

func Flush() error

Flush log messages

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

func FlushTimeout(timeout time.Duration)

FlushTimeout flush logs with timeout.

func Info

func Info(args ...any)

Info logs a message at level Info

func Infof

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

Infof logs a message at level Info

func LevelName

func LevelName(l Level) string

LevelName match

func MustClose added in v0.5.4

func MustClose()

MustClose logger, flush and close all handlers.

IMPORTANT: please call Close() before app exit.

func MustFlush added in v0.2.1

func MustFlush()

MustFlush log messages

func Notice

func Notice(args ...any)

Notice logs a message at level Notice

func Noticef

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

Noticef logs a message at level Notice

func Panic added in v0.1.0

func Panic(args ...any)

Panic logs a message at level Panic

func PanicErr added in v0.3.1

func PanicErr(err error)

PanicErr logs a message at level Panic on err is not nil

func Panicf added in v0.1.0

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

Panicf logs a message at level Panic

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 ...any)

Print logs a message at level PrintLevel

func Printf added in v0.0.3

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

Printf logs a message at level PrintLevel

func Println added in v0.0.3

func Println(args ...any)

Println logs a message at level PrintLevel

func PushHandler added in v0.1.2

func PushHandler(h Handler)

PushHandler to the std logger

func PushHandlers added in v0.1.3

func PushHandlers(hs ...Handler)

PushHandlers to the std logger

func RegisterExitHandler

func RegisterExitHandler(handler func())

RegisterExitHandler register an exit-handler on global exitHandlers

func Reset

func Reset()

Reset the std logger and reset exit handlers

func ResetExitHandlers

func ResetExitHandlers(applyToStd bool)

ResetExitHandlers reset all exitHandlers

func SetExitFunc

func SetExitFunc(fn func(code int))

SetExitFunc to the std logger

func SetFormatter

func SetFormatter(f Formatter)

SetFormatter to std logger

func SetLogLevel added in v0.0.6

func SetLogLevel(l Level)

SetLogLevel max level for the std logger

func StopDaemon added in v0.5.3

func StopDaemon()

StopDaemon stop flush daemon

func Trace

func Trace(args ...any)

Trace logs a message at level Trace

func Tracef

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

Tracef logs a message at level Trace

func Warn

func Warn(args ...any)

Warn logs a message at level Warn

func Warnf

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

Warnf logs a message at level Warn

Types

type CallerFormatFn added in v0.5.3

type CallerFormatFn func(rf *runtime.Frame) (cs string)

CallerFormatFn caller format func

type ClockFn added in v0.3.0

type ClockFn func() time.Time

ClockFn func

func (ClockFn) Now added in v0.3.0

func (fn ClockFn) Now() time.Time

Now implements the Clocker

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

func GetFormatter

func GetFormatter() Formatter

GetFormatter of the std logger

type FormatterFunc

type FormatterFunc func(r *Record) ([]byte, error)

FormatterFunc wrapper definition

func (FormatterFunc) Format

func (fn FormatterFunc) Format(r *Record) ([]byte, error)

Format a log record

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

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(r *Record) ([]byte, error)

Format an log record

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

func LevelByName(ln string) Level

LevelByName convert name to level

func Name2Level

func Name2Level(ln string) (Level, error)

Name2Level convert name to level

func (Level) LowerName

func (l Level) LowerName() string

LowerName get lower level name

func (Level) Name

func (l Level) Name() string

Name get level name

func (Level) ShouldHandling added in v0.1.3

func (l Level) ShouldHandling(curLevel Level) bool

ShouldHandling compare level, if current level <= l, it will be record.

func (Level) String

func (l Level) String() string

String get level name

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 LevelMode added in v0.5.3

type LevelMode uint8

LevelMode define level mode

const (
	// LevelModeList use level list for limit record write
	LevelModeList LevelMode = iota
	// LevelModeMax use max level limit log record write
	LevelModeMax
)

func (LevelMode) String added in v0.5.3

func (m LevelMode) String() string

String return string value

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 Levels added in v0.0.5

type Levels []Level

Levels level list

func (Levels) Contains added in v0.0.5

func (ls Levels) Contains(level Level) bool

Contains given level

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

func New(fns ...LoggerFn) *Logger

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

func NewWithConfig(fns ...LoggerFn) *Logger

NewWithConfig create a new logger with config func

func NewWithHandlers

func NewWithHandlers(hs ...Handler) *Logger

NewWithHandlers create a new logger with handlers

func NewWithName

func NewWithName(name string, fns ...LoggerFn) *Logger

NewWithName create a new logger with name

func (*Logger) AddHandler

func (l *Logger) AddHandler(h Handler)

AddHandler to the logger

func (*Logger) AddHandlers

func (l *Logger) AddHandlers(hs ...Handler)

AddHandlers to the logger

func (*Logger) AddProcessor

func (l *Logger) AddProcessor(p Processor)

AddProcessor to the logger

func (*Logger) AddProcessors

func (l *Logger) AddProcessors(ps ...Processor)

AddProcessors to the logger. alias of AddProcessor()

func (*Logger) Close

func (l *Logger) Close() error

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) Config added in v0.3.0

func (l *Logger) Config(fns ...LoggerFn) *Logger

Config current logger

func (*Logger) Configure

func (l *Logger) Configure(fn LoggerFn) *Logger

Configure current logger. alias of Config()

func (*Logger) Debug

func (l *Logger) Debug(args ...any)

Debug logs a message at level debug

func (*Logger) Debugf

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

Debugf logs a message at level debug

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) Error

func (l *Logger) Error(args ...any)

Error logs a message at level error

func (*Logger) ErrorT added in v0.1.5

func (l *Logger) ErrorT(err error)

ErrorT logs a error type at level error

func (*Logger) Errorf

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

Errorf logs a message at level error

func (*Logger) Exit

func (l *Logger) Exit(code int)

Exit logger handle

func (*Logger) ExitHandlers

func (l *Logger) ExitHandlers() []func()

ExitHandlers get all exitHandlers of the logger

func (*Logger) Fatal

func (l *Logger) Fatal(args ...any)

Fatal logs a message at level fatal

func (*Logger) Fatalf

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

Fatalf logs a message at level fatal

func (*Logger) Fatalln added in v0.2.0

func (l *Logger) Fatalln(args ...any)

Fatalln logs a message at level fatal

func (*Logger) Flush added in v0.1.0

func (l *Logger) Flush() error

Flush flushes all the logs and attempts to "sync" their data to disk. l.mu is held.

func (*Logger) FlushAll

func (l *Logger) FlushAll() error

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

func (l *Logger) FlushTimeout(timeout time.Duration)

FlushTimeout flush logs on limit time.

refer from glog package

func (*Logger) HandlersNum added in v0.5.4

func (l *Logger) HandlersNum() int

HandlersNum returns the number of handlers

func (*Logger) Info

func (l *Logger) Info(args ...any)

Info logs a message at level Info

func (*Logger) Infof

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

Infof logs a message at level Info

func (*Logger) LastErr added in v0.3.2

func (l *Logger) LastErr() error

LastErr fetch, will clear it after read.

func (*Logger) Log

func (l *Logger) Log(level Level, args ...any)

Log a message with level

func (*Logger) Logf

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

Logf a format message with level

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) Name

func (l *Logger) Name() string

Name of the logger

func (*Logger) Notice

func (l *Logger) Notice(args ...any)

Notice logs a message at level notice

func (*Logger) Noticef

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

Noticef logs a message at level notice

func (*Logger) Panic

func (l *Logger) Panic(args ...any)

Panic logs a message at level panic

func (*Logger) Panicf

func (l *Logger) Panicf(format string, args ...any)

Panicf logs a message at level panic

func (*Logger) Panicln added in v0.2.0

func (l *Logger) Panicln(args ...any)

Panicln logs a message at level panic

func (*Logger) PrependExitHandler

func (l *Logger) PrependExitHandler(handler func())

PrependExitHandler prepend register an exit-handler on global exitHandlers

func (*Logger) Print added in v0.0.3

func (l *Logger) Print(args ...any)

Print logs a message at level PrintLevel

func (*Logger) Printf added in v0.0.3

func (l *Logger) Printf(format string, args ...any)

Printf logs a message at level PrintLevel

func (*Logger) Println added in v0.0.3

func (l *Logger) Println(args ...any)

Println logs a message at level PrintLevel

func (*Logger) PushHandler

func (l *Logger) PushHandler(h Handler)

PushHandler to the l. alias of AddHandler()

func (*Logger) PushHandlers added in v0.1.3

func (l *Logger) PushHandlers(hs ...Handler)

PushHandlers to the logger

func (*Logger) PushProcessor

func (l *Logger) PushProcessor(p Processor)

PushProcessor to the logger, alias of AddProcessor()

func (*Logger) Record added in v0.3.0

func (l *Logger) Record() *Record

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) ResetHandlers

func (l *Logger) ResetHandlers()

ResetHandlers for the logger

func (*Logger) ResetProcessors

func (l *Logger) ResetProcessors()

ResetProcessors for the logger

func (*Logger) Reused added in v0.5.5

func (l *Logger) Reused() *Record

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) SetHandlers

func (l *Logger) SetHandlers(hs []Handler)

SetHandlers for the logger

func (*Logger) SetName

func (l *Logger) SetName(name string)

SetName for logger

func (*Logger) SetProcessors

func (l *Logger) SetProcessors(ps []Processor)

SetProcessors for the logger

func (*Logger) StopDaemon added in v0.5.3

func (l *Logger) StopDaemon()

StopDaemon stop flush daemon

func (*Logger) Sync

func (l *Logger) Sync() error

Sync flushes buffered logs (if any). alias of the Flush()

func (*Logger) Trace

func (l *Logger) Trace(args ...any)

Trace logs a message at level trace

func (*Logger) Tracef

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

Tracef logs a message at level trace

func (*Logger) VisitAll

func (l *Logger) VisitAll(fn func(handler Handler) error) error

VisitAll logger handlers

func (*Logger) Warn

func (l *Logger) Warn(args ...any)

Warn logs a message at level Warn

func (*Logger) Warnf

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

Warnf logs a message at level Warn

func (*Logger) Warning

func (l *Logger) Warning(args ...any)

Warning logs a message at level Warn, alias of Logger.Warn()

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Record

WithContext new record with context.Context

func (*Logger) WithCtx added in v0.4.0

func (l *Logger) WithCtx(ctx context.Context) *Record

WithCtx new record with context.Context

func (*Logger) WithData

func (l *Logger) WithData(data M) *Record

WithData new record with data

func (*Logger) WithExtra added in v0.5.5

func (l *Logger) WithExtra(ext M) *Record

WithExtra new record with extra data

func (*Logger) WithField added in v0.3.0

func (l *Logger) WithField(name string, value any) *Record

WithField new record with field

TIP: add field need config Formatter template fields.

func (*Logger) WithFields

func (l *Logger) WithFields(fields M) *Record

WithFields new record with fields

TIP: add field need config Formatter template fields.

func (*Logger) WithTime

func (l *Logger) WithTime(t time.Time) *Record

WithTime new record with time.Time

func (*Logger) WithValue added in v0.5.5

func (l *Logger) WithValue(key string, value any) *Record

WithValue new record with data value

type LoggerFn added in v0.4.0

type LoggerFn func(l *Logger)

LoggerFn func

type M

type M map[string]any

M short name of map[string]any

func (M) String added in v0.2.0

func (m M) String() string

String map to string

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 AddHostname

func AddHostname() Processor

AddHostname to record

func AddUniqueID added in v0.0.3

func AddUniqueID(fieldName string) Processor

AddUniqueID to record

func AppendCtxKeys added in v0.5.1

func AppendCtxKeys(keys ...string) Processor

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.

func (ProcessorFunc) Process

func (fn ProcessorFunc) Process(record *Record)

Process record

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

func WithContext(ctx context.Context) *Record

WithContext new record with context

func WithData

func WithData(data M) *Record

WithData new record with data

func WithExtra added in v0.5.5

func WithExtra(ext M) *Record

WithExtra new record with extra data

func WithField added in v0.5.2

func WithField(name string, value any) *Record

WithField new record with field.

TIP: add field need config Formatter template fields.

func WithFields

func WithFields(fields M) *Record

WithFields new record with fields

TIP: add field need config Formatter template fields.

func WithValue added in v0.5.5

func WithValue(key string, value any) *Record

WithValue new record with data value

func (*Record) AddData

func (r *Record) AddData(data M) *Record

AddData on record

func (*Record) AddExtra

func (r *Record) AddExtra(data M) *Record

AddExtra information on record

func (*Record) AddField

func (r *Record) AddField(name string, val any) *Record

AddField add new field to the record

func (*Record) AddFields

func (r *Record) AddFields(fields M) *Record

AddFields add new fields to the record

func (*Record) AddValue

func (r *Record) AddValue(key string, value any) *Record

AddValue add Data value to record

func (*Record) Copy

func (r *Record) Copy() *Record

Copy new record from old record

func (*Record) Debug

func (r *Record) Debug(args ...any)

Debug logs a message at level Debug

func (*Record) Debugf

func (r *Record) Debugf(format string, args ...any)

Debugf logs a message at level Debug

func (*Record) Error

func (r *Record) Error(args ...any)

Error logs a message at level Error

func (*Record) Errorf

func (r *Record) Errorf(format string, args ...any)

Errorf logs a message at level Error

func (*Record) Fatal

func (r *Record) Fatal(args ...any)

Fatal logs a message at level Fatal

func (*Record) Fatalf

func (r *Record) Fatalf(format string, args ...any)

Fatalf logs a message at level Fatal

func (*Record) Fatalln added in v0.2.0

func (r *Record) Fatalln(args ...any)

Fatalln logs a message at level Fatal

func (*Record) Field added in v0.5.2

func (r *Record) Field(key string) any

Field value get from record

func (*Record) GoString added in v0.3.0

func (r *Record) GoString() string

GoString of the record

func (*Record) Info

func (r *Record) Info(args ...any)

Info logs a message at level Info

func (*Record) Infof

func (r *Record) Infof(format string, args ...any)

Infof logs a message at level Info

func (*Record) Init added in v0.2.0

func (r *Record) Init(lowerLevelName bool)

Init something for record(eg: time, level name).

func (*Record) LevelName

func (r *Record) LevelName() string

LevelName get

func (*Record) Log

func (r *Record) Log(level Level, args ...any)

Log a message with level

func (*Record) Logf

func (r *Record) Logf(level Level, format string, args ...any)

Logf a message with level

func (*Record) Notice

func (r *Record) Notice(args ...any)

Notice logs a message at level Notice

func (*Record) Noticef

func (r *Record) Noticef(format string, args ...any)

Noticef logs a message at level Notice

func (*Record) Panic

func (r *Record) Panic(args ...any)

Panic logs a message at level Panic

func (*Record) Panicf

func (r *Record) Panicf(format string, args ...any)

Panicf logs a message at level Panic

func (*Record) Panicln added in v0.2.0

func (r *Record) Panicln(args ...any)

Panicln logs a message at level Panic

func (*Record) Print added in v0.2.0

func (r *Record) Print(args ...any)

Print logs a message at level Print

func (*Record) Printf added in v0.2.0

func (r *Record) Printf(format string, args ...any)

Printf logs a message at level Print

func (*Record) Println added in v0.2.0

func (r *Record) Println(args ...any)

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

func (r *Record) Reused() *Record

Reused set record is reused, will not be released on after write.

func (*Record) SetContext

func (r *Record) SetContext(ctx context.Context) *Record

SetContext on record

func (*Record) SetCtx added in v0.4.0

func (r *Record) SetCtx(ctx context.Context) *Record

SetCtx on record

func (*Record) SetData

func (r *Record) SetData(data M) *Record

SetData on record

func (*Record) SetExtra

func (r *Record) SetExtra(data M) *Record

SetExtra information on record

func (*Record) SetExtraValue added in v0.2.0

func (r *Record) SetExtraValue(k string, v any)

SetExtraValue on record

func (*Record) SetFields

func (r *Record) SetFields(fields M) *Record

SetFields to the record

func (*Record) SetTime

func (r *Record) SetTime(t time.Time) *Record

SetTime on record

func (*Record) Trace

func (r *Record) Trace(args ...any)

Trace logs a message at level Trace

func (*Record) Tracef

func (r *Record) Tracef(format string, args ...any)

Tracef logs a message at level Trace

func (*Record) Value added in v0.5.2

func (r *Record) Value(key string) any

Value get Data value from record

func (*Record) Warn added in v0.3.0

func (r *Record) Warn(args ...any)

Warn logs a message at level Warn

func (*Record) Warnf added in v0.3.0

func (r *Record) Warnf(format string, args ...any)

Warnf logs a message at level Warn

func (*Record) WithContext

func (r *Record) WithContext(ctx context.Context) *Record

WithContext on record

func (*Record) WithCtx added in v0.5.1

func (r *Record) WithCtx(ctx context.Context) *Record

WithCtx on record

func (*Record) WithData

func (r *Record) WithData(data M) *Record

WithData on record

func (*Record) WithError

func (r *Record) WithError(err error) *Record

WithError on record

func (*Record) WithField

func (r *Record) WithField(name string, val any) *Record

WithField with a new field to record

Note: add field need config Formatter template fields.

func (*Record) WithFields

func (r *Record) WithFields(fields M) *Record

WithFields with new fields to record

Note: add field need config Formatter template fields.

func (*Record) WithTime

func (r *Record) WithTime(t time.Time) *Record

WithTime set the record time

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 StringMap

type StringMap = map[string]string

StringMap string map short name

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 Std

func Std() *SugaredLogger

Std get std logger

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

func (*SugaredLogger) Reset

func (sl *SugaredLogger) Reset()

Reset the logger

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 (*TextFormatter) Configure added in v0.5.3

func (f *TextFormatter) Configure(fn func(*TextFormatter)) *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

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.

Jump to

Keyboard shortcuts

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