slog

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 5, 2022 License: MIT Imports: 19 Imported by: 171

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 at the same time, and buffer buffered writing is enabled by default
    • See ./handler folder for more built-in implementations

NEW: v0.3.0 discards the various handlers that were originally implemented, and the unified abstraction is FlushCloseHandler SyncCloseHandler WriteCloserHandler IOWriterHandler Several processors that support different types of writers. Makes it easier to build custom handlers, built-in handlers are basically composed of them.

中文说明

中文说明请阅读 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()

l.Trace("this is a simple log message")
l.Debug("this is a simple log message")

Change the default logger log output style:

h.GetFormatter().(*slog.TextFormatter).Template = 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 --{ With Formatter

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"

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.

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

Output log to file:

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

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

Output log to file and rotate automatically:

func NewSizeRotateFile(logfile string, maxSize int, fns ...ConfigFn) (*SyncCloseHandler, error) // Automatic rotating according to file size
func NewTimeRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error) // Automatic rotating according to time
// 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.MustFlush()

	// DangerLevels 包含: slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel
	h1 := handler.MustFileHandler("/tmp/error.log", handler.WithLogLevels(slog.DangerLevels))

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

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

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

Tip: If write buffering buffer is enabled, be sure to call logger.Flush() 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_00001
size-rotate-file.log.122915_00002
Quickly create a Handler instance based on config
	testFile := "testdata/error.log"

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

	l := slog.NewWithHandlers(h)
Use Builder to quickly create Handler instances
	testFile := "testdata/info.log"

	h := handler.NewBuilder().
		With(
			handler.WithLogfile(testFile),
			handler.WithBuffSize(1024*8),
			handler.WithLogLevels(slog.NormalLevels),
			handler.WithBuffMode(handler.BuffModeBite),
		).
		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

Testing and benchmark

Unit tests

run unit tests:

go test ./...
Benchmarks
make test-bench

record ad 2022.04.27

% make test-bench
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz
BenchmarkZapNegative
BenchmarkZapNegative-4                  128133166               93.97 ns/op          192 B/op          1 allocs/op
BenchmarkZeroLogNegative
BenchmarkZeroLogNegative-4              909583207               13.41 ns/op            0 B/op          0 allocs/op
BenchmarkPhusLogNegative
BenchmarkPhusLogNegative-4              784099310               15.24 ns/op            0 B/op          0 allocs/op
BenchmarkLogrusNegative
BenchmarkLogrusNegative-4               289939296               41.60 ns/op           16 B/op          1 allocs/op
BenchmarkGookit_SlogNegative
> BenchmarkGookit_SlogNegative-4           29131203               417.4 ns/op           125 B/op          4 allocs/op
BenchmarkZapPositive
BenchmarkZapPositive-4                   9910075              1219 ns/op             192 B/op          1 allocs/op
BenchmarkZeroLogPositive
BenchmarkZeroLogPositive-4              13966810               871.0 ns/op             0 B/op          0 allocs/op
BenchmarkPhusLogPositive
BenchmarkPhusLogPositive-4              26743148               446.2 ns/op             0 B/op          0 allocs/op
BenchmarkLogrusPositive
BenchmarkLogrusPositive-4                2658482              4481 ns/op             608 B/op         17 allocs/op
BenchmarkGookit_SlogPositive
> BenchmarkGookit_SlogPositive-4            8349562              1441 ns/op             165 B/op          6 allocs/op
PASS
ok      command-line-arguments  146.669s

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
	// CallerFlagPkg report full package name.
	// eg: "github.com/gookit/slog_test"
	CallerFlagPkg
	// 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"
View Source
const NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"

Variables

View Source
var (
	// FieldKeyData define the key name for Record.Data
	FieldKeyData = "data"
	FieldKeyTime = "time"
	FieldKeyDate = "date"

	FieldKeyDatetime  = "datetime"
	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 = "level"
	// FieldKeyError Define the key when adding errors using WithError.
	FieldKeyError = "error"
	FieldKeyExtra = "extra"

	FieldKeyChannel = "channel"
	FieldKeyMessage = "message"
)
View Source
var (
	// DefaultChannelName for log record
	DefaultChannelName = "application"
	DefaultTimeFormat  = "2006/01/02T15:04:05"

	// DoNothingOnExit handler. use for testing.
	DoNothingOnExit  = func(code int) {}
	DoNothingOnPanic = func(v interface{}) {}

	DefaultPanicFn = func(v interface{}) {
		panic(v)
	}
	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 = Levels{InfoLevel, NoticeLevel, DebugLevel, TraceLevel}

	// 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",
	}
)
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 Configure

func Configure(fn func(l *SugaredLogger))

Configure the std logger

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs a message at level Debug

func EncodeToString added in v0.2.0

func EncodeToString(v interface{}) string

EncodeToString data to string

func Error

func Error(args ...interface{})

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 ...interface{})

Errorf logs a message at level Error

func Exit

func Exit(code int)

Exit runs all the logger 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 ...interface{})

Fatal logs a message at level Fatal

func Fatalf

func Fatalf(format string, args ...interface{})

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

FlushDaemon run flush handle on daemon

Usage:

go slog.FlushDaemon()

func FlushTimeout added in v0.1.1

func FlushTimeout(timeout time.Duration)

FlushTimeout flush logs with timeout.

func Info

func Info(args ...interface{})

Info logs a message at level Info

func Infof

func Infof(format string, args ...interface{})

Infof logs a message at level Info

func LevelName

func LevelName(l Level) string

LevelName match

func MustFlush added in v0.2.1

func MustFlush()

MustFlush log messages

func Notice

func Notice(args ...interface{})

Notice logs a message at level Notice

func Noticef

func Noticef(format string, args ...interface{})

Noticef logs a message at level Notice

func Panic added in v0.1.0

func Panic(args ...interface{})

Panic logs a message at level Panic

func Panicf added in v0.1.0

func Panicf(format string, args ...interface{})

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

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 for the std logger

func Trace

func Trace(args ...interface{})

Trace logs a message at level Trace

func Tracef

func Tracef(format string, args ...interface{})

Tracef logs a message at level Trace

func Warn

func Warn(args ...interface{})

Warn logs a message at level Warn

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs a message at level Warn

Types

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 struct {
	// contains filtered or unexported fields
}

Formattable definition

func (*Formattable) Format added in v0.3.0

func (f *Formattable) Format(record *Record) ([]byte, error)

Format log record to bytes

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 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 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
}

JSONFormatter definition

func NewJSONFormatter

func NewJSONFormatter(fn ...func(*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, 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 {
	FormattableHandler
	IsHandling(level Level) bool
}

LevelFormattable support limit log levels and provide formatter

type LevelWithFormatter added in v0.3.0

type LevelWithFormatter struct {
	Formattable
	// Level for log message. if current level >= Level will log message
	Level Level
}

LevelWithFormatter struct definition

- support set log formatter - only support set one log level

func NewLvFormatter added in v0.3.0

func NewLvFormatter(lv Level) *LevelWithFormatter

NewLvFormatter create new 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

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 {
	Formattable
	// 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

type Logger

type Logger struct {

	// LowerLevelName use lower level name
	LowerLevelName bool
	// ReportCaller on write log record
	ReportCaller bool
	CallerSkip   int
	CallerFlag   uint8
	// TimeClock custom time clock, timezone
	TimeClock ClockFn

	// custom exit, panic handle.
	ExitFunc  func(code int)
	PanicFunc func(v interface{})
	// contains filtered or unexported fields
}

Logger log dispatcher definition.

The logger implements the `github.com/gookit/gsr.Logger`

func New

func New() *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(fn func(l *Logger)) *Logger

NewWithConfig create a new logger with config func

func NewWithHandlers

func NewWithHandlers(hs ...Handler) *Logger

NewWithHandlers create an new logger with handlers

func NewWithName

func NewWithName(name string) *Logger

NewWithName create an 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

func (*Logger) Close

func (l *Logger) Close() error

Close the logger

func (*Logger) Config added in v0.3.0

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

Config current logger

func (*Logger) Configure

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

Configure current logger

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

Debug logs a message at level Debug

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

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 ...interface{})

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 ...interface{})

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 ...interface{})

Fatal logs a message at level Fatal

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf logs a message at level Fatal

func (*Logger) Fatalln added in v0.2.0

func (l *Logger) Fatalln(args ...interface{})

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

FlushDaemon run flush handle on daemon

Usage:

go slog.FlushDaemon()

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

func (l *Logger) Info(args ...interface{})

Info logs a message at level Info

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs a message at level Info

func (*Logger) Log

func (l *Logger) Log(level Level, args ...interface{})

Log a message with level

func (*Logger) Logf

func (l *Logger) Logf(level Level, format string, args ...interface{})

Logf a format message with level

func (*Logger) MustFlush added in v0.3.0

func (l *Logger) MustFlush()

MustFlush flush logs. will ignore error

func (*Logger) Name

func (l *Logger) Name() string

Name of the logger

func (*Logger) Notice

func (l *Logger) Notice(args ...interface{})

Notice logs a message at level Notice

func (*Logger) Noticef

func (l *Logger) Noticef(format string, args ...interface{})

Noticef logs a message at level Notice

func (*Logger) Panic

func (l *Logger) Panic(args ...interface{})

Panic logs a message at level Panic

func (*Logger) Panicf

func (l *Logger) Panicf(format string, args ...interface{})

Panicf logs a message at level Panic

func (*Logger) Panicln added in v0.2.0

func (l *Logger) Panicln(args ...interface{})

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 ...interface{})

Print logs a message at level PrintLevel

func (*Logger) Printf added in v0.0.3

func (l *Logger) Printf(format string, args ...interface{})

Printf logs a message at level PrintLevel

func (*Logger) Println added in v0.0.3

func (l *Logger) Println(args ...interface{})

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 for 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

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

func (l *Logger) Sync() error

Sync flushes buffered logs (if any).

alias of the Flush()

func (*Logger) Trace

func (l *Logger) Trace(args ...interface{})

Trace logs a message at level Trace

func (*Logger) Tracef

func (l *Logger) Tracef(format string, args ...interface{})

Tracef logs a message at level Trace

func (*Logger) VisitAll

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

VisitAll logger handlers

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn logs a message at level Warn

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf logs a message at level Warn

func (*Logger) Warning

func (l *Logger) Warning(args ...interface{})

Warning logs a message at level Warn

func (*Logger) WithContext

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

WithContext new record with context.Context

func (*Logger) WithData

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

WithData new record with data

func (*Logger) WithField added in v0.3.0

func (l *Logger) WithField(name string, value interface{}) *Record

WithField new record with field

func (*Logger) WithFields

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

WithFields new record with fields

func (*Logger) WithTime

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

WithTime new record with time.Time

type M

type M map[string]interface{}

M short name of map[string]interface{}

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 an processor
	AddProcessor(Processor)
	// ProcessRecord handle an 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

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  time.Time
	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
	// contains filtered or unexported fields
}

Record a log record definition

func WithData

func WithData(data M) *Record

WithData new record with data

func WithFields

func WithFields(fields M) *Record

WithFields new record with fields

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 interface{}) *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 interface{}) *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 ...interface{})

Debug logs a message at level Debug

func (*Record) Debugf

func (r *Record) Debugf(format string, args ...interface{})

Debugf logs a message at level Debug

func (*Record) Error

func (r *Record) Error(args ...interface{})

Error logs a message at level Error

func (*Record) Errorf

func (r *Record) Errorf(format string, args ...interface{})

Errorf logs a message at level Error

func (*Record) Fatal

func (r *Record) Fatal(args ...interface{})

Fatal logs a message at level Fatal

func (*Record) Fatalf

func (r *Record) Fatalf(format string, args ...interface{})

Fatalf logs a message at level Fatal

func (*Record) Fatalln added in v0.2.0

func (r *Record) Fatalln(args ...interface{})

Fatalln logs a message at level Fatal

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 ...interface{})

Info logs a message at level Info

func (*Record) Infof

func (r *Record) Infof(format string, args ...interface{})

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.

func (*Record) LevelName

func (r *Record) LevelName() string

LevelName get

func (*Record) Log

func (r *Record) Log(level Level, args ...interface{})

Log a message with level

func (*Record) Logf

func (r *Record) Logf(level Level, format string, args ...interface{})

Logf a message with level

func (*Record) Notice

func (r *Record) Notice(args ...interface{})

Notice logs a message at level Notice

func (*Record) Noticef

func (r *Record) Noticef(format string, args ...interface{})

Noticef logs a message at level Notice

func (*Record) Panic

func (r *Record) Panic(args ...interface{})

Panic logs a message at level Panic

func (*Record) Panicf

func (r *Record) Panicf(format string, args ...interface{})

Panicf logs a message at level Panic

func (*Record) Panicln added in v0.2.0

func (r *Record) Panicln(args ...interface{})

Panicln logs a message at level Panic

func (*Record) Print added in v0.2.0

func (r *Record) Print(args ...interface{})

Print logs a message at level Print

func (*Record) Printf added in v0.2.0

func (r *Record) Printf(format string, args ...interface{})

Printf logs a message at level Print

func (*Record) Println added in v0.2.0

func (r *Record) Println(args ...interface{})

Println logs a message at level Print

func (*Record) SetContext

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

SetContext 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 interface{})

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 ...interface{})

Trace logs a message at level Trace

func (*Record) Tracef

func (r *Record) Tracef(format string, args ...interface{})

Tracef logs a message at level Trace

func (*Record) Warn added in v0.3.0

func (r *Record) Warn(args ...interface{})

Warn logs a message at level Warn

func (*Record) Warnf added in v0.3.0

func (r *Record) Warnf(format string, args ...interface{})

Warnf logs a message at level Warn

func (*Record) WithContext

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

WithContext 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 interface{}) *Record

WithField with a new field to record

func (*Record) WithFields

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

WithFields with new fields to record

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 ...interface{})
	Logf(level Level, format string, v ...interface{})
}

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 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 NewStdLogger added in v0.2.0

func NewStdLogger() *SugaredLogger

NewStdLogger instance

func NewSugaredLogger

func NewSugaredLogger(output io.Writer, level Level) *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

func (*SugaredLogger) Config added in v0.3.0

func (sl *SugaredLogger) Config(fn func(sl *SugaredLogger)) *SugaredLogger

Config current logger

func (*SugaredLogger) Configure

func (sl *SugaredLogger) Configure(fn func(sl *SugaredLogger)) *SugaredLogger

Configure 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 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 EncodeToString()
	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) 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

Directories

Path Synopsis
Package handler provide useful common log handlers.
Package handler provide useful common log handlers.

Jump to

Keyboard shortcuts

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