log

package module
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2022 License: Apache-2.0 Imports: 12 Imported by: 1

README

Go Log Build Status GoDoc License

Provide a simple, flexible, extensible, powerful and structured logger based on the level, which has done the better balance between the flexibility and the performance. It is inspired by log15, logrus, go-kit and zerolog, which collects the log message with the key-value contexts, encodes them into the buffer, then writes the encoded log from the buffer into the underlying writer.

Features

  • Support Go1.7+.
  • Compatible with the stdlib log.Printf.
  • The better performance, see Benchmark.
    • Lazy evaluation of expensive operations.
    • Avoid to allocate the memory on heap as far as possible.
    • Encode in real time or pre-encode the key-value contexts into the buffer cache.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Support to customize the log encoder and writer.
  • Provide the simple and easy-used api interface.

Example

package main

import (
    "errors"
    "flag"

    "github.com/xgfone/go-log"
)

var logfile string
var loglevel string

func logError(err error, msg string, kvs ...interface{}) {
    if err == nil {
        return
    }
    log.Level(log.LvlError, 1).Kvs(kvs...).Kv("err", err).Printf(msg)
}

func main() {
    // Parse the CLI options.
    flag.StringVar(&logfile, "logfile", "", "The log file path, default to stderr.")
    flag.StringVar(&loglevel, "loglevel", "info", "The log level, such as debug, info, etc.")
    flag.Parse()

    // Configure the logger.
    writer := log.FileWriter(logfile, "100M", 100)
    defer writer.Close()
    log.SetWriter(writer)
    log.SetLevel(log.ParseLevel(loglevel))

    // Emit the log.
    log.Debug().Kv("key1", "value1").Print("msg1") // no log output.
    log.Info().Kv("key2", "value2").Print("msg2")
    log.Level(log.LvlInfo, 0).Kv("key3", "value3").Printf("msg3")
    logError(nil, "msg4", "key4", "value4", "key5", 555, "key6", "value6")
    logError(errors.New("error"), "msg7", "key8", 888, "key9", "value9")

    // For Clild Logger
    child1Logger := log.WithName("child1")
    child2Logger := child1Logger.WithName("child2")
    child1Logger.Info().Kv("ckey1", "cvalue1").Print("msg8")
    child2Logger.Info().Kv("ckey2", "cvalue2").Printf("msg9")

    // $ go run main.go
    // {"t":"2021-12-17T00:04:44.8609884+08:00","lvl":"info","caller":"main.go:34:main","key2":"value2","msg":"msg2"}
    // {"t":"2021-12-17T00:04:44.8660577+08:00","lvl":"info","caller":"main.go:35:main","key3":"value3","msg":"msg3"}
    // {"t":"2021-12-17T00:04:44.8671207+08:00","lvl":"error","caller":"main.go:37:main","key8":888,"key9":"value9","err":"error","msg":"msg7"}
    // {"t":"2021-12-17T00:04:44.8671207+08:00","lvl":"info","logger":"child1","caller":"main.go:42:main","ckey1":"cvalue1","msg":"msg8"}
    // {"t":"2021-12-17T00:04:44.8678731+08:00","lvl":"info","logger":"child1.child2","caller":"main.go:43:main","ckey2":"cvalue2","msg":"msg9"}
}
logr
// logr.go
package main

import (
    "fmt"

    "github.com/go-logr/logr"
    "github.com/xgfone/go-log"
)

// NewLogSink returns a logr sink based on the key-value logger.
func NewLogSink(logger log.Logger) logr.LogSink {
    return &logSink{logger: logger}
}

const maxLevel = log.LvlWarn - log.LvlInfo - 1

type logSink struct {
    logger log.Logger
}

func (l *logSink) Init(info logr.RuntimeInfo) {
    l.logger = l.logger.WithDepth(info.CallDepth + 1)
}

func (l *logSink) Enabled(level int) bool {
    if level > maxLevel {
        panic(fmt.Errorf("invalid level '%d': only allow [0, %d]", level, maxLevel))
    }
    return l.logger.Enabled(log.LvlInfo + level)
}

func (l *logSink) Info(level int, msg string, keysAndValues ...interface{}) {
    if level > maxLevel {
        panic(fmt.Errorf("invalid level '%d': only allow [0, %d]", level, maxLevel))
    }
    l.logger.Level(log.LvlInfo+level, l.logger.Depth()+1).Kvs(keysAndValues...).Printf(msg)
}

func (l *logSink) Error(err error, msg string, keysAndValues ...interface{}) {
    l.logger.Error().Kvs(keysAndValues...).Kv("err", err).Printf(msg)
}

func (l *logSink) WithName(name string) logr.LogSink {
    return &logSink{l.logger.WithName(name)}
}

func (l *logSink) WithValues(keysAndValues ...interface{}) logr.LogSink {
    return &logSink{l.logger.WithContexts(keysAndValues...)}
}

func (l *logSink) WithCallDepth(depth int) logr.LogSink {
    return &logSink{l.logger.WithDepth(depth + 2)}
}
// main.go
package main

import (
    "errors"

    "github.com/go-logr/logr"
    "github.com/xgfone/go-log"
)

func logIfErr(logger logr.Logger, err error, msg string, kvs ...interface{}) {
    if err != nil {
        logger.Error(err, msg, kvs...)
    }
}

func main() {
    _logger := log.New("test").
        WithHooks(log.Caller("caller")). // Add the caller context
        WithLevel(log.LvlInfo + 3)       // Only output the logs that V is not less than 3

    logger := logr.New(NewLogSink(_logger))
    logger.Info("msg1", "k11", "v11", "k12", "v12") // The log is not be output.
    logger.Error(errors.New("error"), "msg2", "k2", "v2")

    logger = logger.V(6) // V must be between 0 and 19, that's, [0, 19].
    logger.Info("msg3", "k3", "v3")
    logger.Error(errors.New("error"), "msg4", "k4", "v4")

    logger = logger.WithName("name")
    logger.Info("msg5", "k5", "v5")
    logger.Error(errors.New("error"), "msg6", "k6", "v6")

    logger = logger.WithValues("k0", "v0")
    logger.Info("msg7", "k7", "v7")
    logger.Error(errors.New("error"), "msg8", "k8", "v8")

    logger = logger.WithCallDepth(1)
    logIfErr(logger, errors.New("error"), "msg9", "k9", "v9")
    logIfErr(logger, nil, "msg10", "k10", "v10")

    // $ go run logr.go main.go
    // {"t":"2021-12-17T00:16:10.1478129+08:00","lvl":"error","logger":"test","caller":"main.go:23:main","k2":"v2","err":"error","msg":"msg2"}
    // {"t":"2021-12-17T00:16:10.1535681+08:00","lvl":"info6","logger":"test","k3":"v3","msg":"msg3"}
    // {"t":"2021-12-17T00:16:10.1541601+08:00","lvl":"error","logger":"test","caller":"main.go:27:main","k4":"v4","err":"error","msg":"msg4"}
    // {"t":"2021-12-17T00:16:10.1546859+08:00","lvl":"info6","logger":"test.name","k5":"v5","msg":"msg5"}
    // {"t":"2021-12-17T00:16:10.1546859+08:00","lvl":"error","logger":"test.name","caller":"main.go:31:main","k6":"v6","err":"error","msg":"msg6"}
    // {"t":"2021-12-17T00:16:10.1552482+08:00","lvl":"info6","logger":"test.name","k0":"v0","k7":"v7","msg":"msg7"}
    // {"t":"2021-12-17T00:16:10.1552482+08:00","lvl":"error","logger":"test.name","k0":"v0","caller":"main.go:35:main","k8":"v8","err":"error","msg":"msg8"}
    // {"t":"2021-12-17T00:16:10.1558789+08:00","lvl":"error","logger":"test.name","k0":"v0","caller":"main.go:38:main","k9":"v9","err":"error","msg":"msg9"}
}
Encoder
type Encoder interface {
    // Start starts to encode the log record into the buffer dst.
    Start(dst []byte, loggerName string, level int) []byte

    // Encode encodes the key-value with the stack depth into the buffer dst.
    Encode(dst []byte, key string, value interface{}) []byte

    // End ends to encode the log record with the message into the buffer dst.
    End(dst []byte, msg string) []byte
}

This pakcage has implemented the JSON encoder JSONEncoder, but you can customize yourself, such as TextEncoder.

Writer

The logger uses the stdlib io.Writer interface as the log writer.

In order to support to write the leveled log, you can provide a LevelWriter to the log engine, which prefers to try to use LevelWriter to write the log into it.

type LevelWriter interface {
    WriteLevel(level int, data []byte) (n int, err error)
    io.Writer
}

The package provides an additional writer based on the file, that's, FileWriter.

Sampler

The logger engine provides the sampler policy for each logger to filter the log message by the logger name and level during the program is running.

type Sampler interface {
    // Sample reports whether the log message should be sampled.
    // If the log message should be sampled, return true. Or, return false,
    // that's, the log message will be discarded.
    Sample(loggerName string, level int) bool
}

Notice: in order to switch the level of all the loggers once, you maybe use the global level function SetGlobalLevel, such as SetGlobalLevel(LvlError), which will disable all the log messages whose level is lower than LvlError.

Lazy evaluation

The logger provides the hook Hook to support the Lazy evaluation.

type Hook interface {
    Run(logger Logger, loggerName string, level int, depth int)
}

The package provides a dynamic key-value context Caller to calculate the file and line where the caller is.

package main

import "github.com/xgfone/go-log"

func main() {
    logger := log.New("root").WithHooks(log.Caller("caller"))
    logger.Info().Kv("key", "value").Printf("msg")

    // $ go run main.go
    // {"t":"2021-12-12T15:09:41.6890462+08:00","lvl":"info","logger":"root","caller":"main.go:7:main","key":"value","msg":"msg"}
}

Not only the lazy evaluation, but the hook is also used to do others, such as the counter of the level logs.

Performance

The log framework itself has no any performance costs and the key of the bottleneck is the encoder.

HP Laptop 14s-dr2014TU
go: 1.17.3
goos: windows
goarch: amd64
cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz

Benchmark Package:

Function ops ns/op bytes/opt allocs/op
BenchmarkJSONEncoderDisabled-8 325, 556, 422 3.649 0 0
BenchmarkJSONEncoderEmpty-8 71, 245, 855 17.71 0 0
BenchmarkJSONEncoderInfo-8 64, 453, 407 17.84 0 0
BenchmarkJSONEncoderWith8Contexts-8 63, 589, 971 17.87 0 0
BenchmarkJSONEncoderWith8KeyValues-8 9, 351, 409 121.9 128 8
BenchmarkJSONEncoderWithOptimized8KVs-8 14, 620, 470 78.71 0 0

Documentation

Overview

Package log provides a simple, flexible, extensible, powerful and structured logger based on the level, which has done the better balance between the flexibility and the performance. It collects the log message with the key-value contexts, encodes them into the buffer, then writes the encoded log from the buffer into the underlying writer.

Features

  • Support `Go1.7+`.
  • Compatible with the stdlib `log.Printf`.
  • The better performance:
  • Lazy evaluation of expensive operations.
  • Avoid to allocate the memory on heap as far as possible.
  • Encode in real time or pre-encode the key-value contexts into the buffer cache.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Support to customize the log encoder and writer.
  • Provide the simple and easy-used api interface.

Example

package main

import (
    "errors"
    "flag"

    "github.com/xgfone/go-log"
)

var logfile string
var loglevel string

func logError(err error, msg string, kvs ...interface{}) {
    if err == nil {
        return
    }
    log.Level(log.LvlError, 1).Kvs(kvs...).Kv("err", err).Printf(msg)
}

func main() {
    // Parse the CLI options.
    flag.StringVar(&logfile, "logfile", "", "The log file path, default to stderr.")
    flag.StringVar(&loglevel, "loglevel", "info", "The log level, such as debug, info, etc.")
    flag.Parse()

    // Configure the logger.
    writer := log.FileWriter(logfile, "100M", 100)
    defer writer.Close()
    log.SetWriter(writer)
    log.SetLevel(log.ParseLevel(loglevel))

    // Emit the log.
    log.Debug().Kv("key1", "value1").Print("msg1") // no log output.
    log.Info().Kv("key2", "value2").Print("msg2")
    log.Level(log.LvlInfo, 0).Kv("key3", "value3").Printf("msg3")
    logError(nil, "msg4", "key4", "value4", "key5", 555, "key6", "value6")
    logError(errors.New("error"), "msg7", "key8", 888, "key9", "value9")

    // For Clild Logger
    child1Logger := log.WithName("child1")
    child2Logger := child1Logger.WithName("child2")
    child1Logger.Info().Kv("ckey1", "cvalue1").Print("msg8")
    child2Logger.Info().Kv("ckey2", "cvalue2").Printf("msg9")

    // $ go run main.go
    // {"t":"2021-12-17T00:04:44.8609884+08:00","lvl":"info","caller":"main.go:34:main","key2":"value2","msg":"msg2"}
    // {"t":"2021-12-17T00:04:44.8660577+08:00","lvl":"info","caller":"main.go:35:main","key3":"value3","msg":"msg3"}
    // {"t":"2021-12-17T00:04:44.8671207+08:00","lvl":"error","caller":"main.go:37:main","key8":888,"key9":"value9","err":"error","msg":"msg7"}
    // {"t":"2021-12-17T00:04:44.8671207+08:00","lvl":"info","logger":"child1","caller":"main.go:42:main","ckey1":"cvalue1","msg":"msg8"}
    // {"t":"2021-12-17T00:04:44.8678731+08:00","lvl":"info","logger":"child1.child2","caller":"main.go:43:main","ckey2":"cvalue2","msg":"msg9"}
}

Index

Constants

View Source
const (
	LvlTrace   = int(0)
	LvlDebug   = int(20)
	LvlInfo    = int(40)
	LvlWarn    = int(60)
	LvlError   = int(80)
	LvlAlert   = int(100)
	LvlPanic   = int(120)
	LvlFatal   = int(126)
	LvlDisable = int(127)
)

Predefine some levels.

Variables

View Source
var CallerFormatFunc = func(file, name string, line int) string {
	if index := strings.LastIndexByte(name, '.'); index > -1 {
		name = name[index+1:]
	}
	return fmt.Sprintf("%s:%s:%d", filepath.Base(file), name, line)
}

CallerFormatFunc is used to format the file, name and line of the caller.

View Source
var DefaultBufferCap = 256

DefaultBufferCap is the default capacity of the buffer to encode the log.

View Source
var DefaultLogger = New("").WithHooks(Caller("caller"))

DefaultLogger is the default global logger.

View Source
var FormatLevel func(level int) string = formatLevel

FormatLevel is used to format the level to string.

View Source
var OnExit func()

OnExit is called before the program exits when to emit the log with LvlFatal.

Functions

func Ef

func Ef(err error, format string, args ...interface{})

Ef is equal to DefaultLogger.Error().Kv("err", err).Printf(format, args...).

func Err added in v0.15.0

func Err(err error, msg string, keysAndValues ...interface{})

Err logs the error message and key-values with the ERROR level.

func FileWriter

func FileWriter(filename, filesize string, filenum int) io.WriteCloser

FileWriter returns a writer based the file, which uses NewSizedRotatingFile to generate the file writer. If filename is "", however, it will return an os.Stderr writer instead.

filesize is parsed by ParseSize to get the size of the log file. If it is "", it is "100M" by default.

filenum is the number of the log file. If it is 0 or negative, it will be reset to 100.

Notice: if the directory in where filename is does not exist, it will be created automatically.

func GetCallStack added in v0.15.0

func GetCallStack(skip int) []string

GetCallStack returns the call stacks.

func GetGlobalLevel added in v0.7.0

func GetGlobalLevel() int

GetGlobalLevel returns the global level setting.

Notice: if the returned level value is negative, it represents that no global level is set.

func GetLevel added in v0.4.0

func GetLevel() int

GetLevel is equal to DefaultLogger.GetLevel().

func GlobalDisableSampling added in v0.7.0

func GlobalDisableSampling(disable bool)

GlobalDisableSampling is used to disable all the samplings globally.

func IfErr added in v0.6.0

func IfErr(err error, msg string, keysAndValues ...interface{})

IfErr is the same as Err, but only if err is not equal to nil.

func LevelIsValid added in v0.8.0

func LevelIsValid(level int) bool

LevelIsValid reports whether the level is valid, that's, [LvlTrace, LvlDisable].

func ParseLevel added in v0.7.0

func ParseLevel(level string, defaultLevel ...int) int

ParseLevel parses a string to the level.

Support the level string as follow, which is case insensitive:

trace
debug
info
warn
error
alert
panic
fatal
disable

func SetEncoder added in v0.7.0

func SetEncoder(enc Encoder)

SetEncoder is eqaul to DefaultLogger.SetEncoder(enc).

func SetGlobalLevel added in v0.7.0

func SetGlobalLevel(level int)

SetGlobalLevel sets the global level, which will act on all the logger.

If the level is negative, it will unset the global level.

func SetLevel added in v0.4.0

func SetLevel(level int)

SetLevel is equal to DefaultLogger.SetLevel(level).

func SetLevelFormat added in v0.14.0

func SetLevelFormat(format func(level int) string)

SetLevelFormat is equal to DefaultLogger.SetLevelFormat(format).

func SetWriter added in v0.7.0

func SetWriter(w io.Writer)

SetWriter is eqaul to DefaultLogger.SetWriter(w).

func StdLogger added in v0.13.0

func StdLogger(prefix string, level int) *log.Logger

StdLogger is equal to DefaultLogger.StdLogger(prefix, level).

func WrapPanic added in v0.2.0

func WrapPanic(keysAndValues ...interface{})

WrapPanic wraps and logs the panic, which should be called directly with defer, For example,

defer WrapPanic()
defer WrapPanic("key1", "value1")
defer WrapPanic("key1", "value1", "key2", "value2")
defer WrapPanic("key1", "value1", "key2", "value2", "key3", "value3")

Types

type Emitter added in v0.10.0

type Emitter struct {
	// contains filtered or unexported fields
}

Emitter is used to emit the log message.

func Alert added in v0.8.0

func Alert(kvs ...interface{}) *Emitter

Alert is equal to DefaultLogger.Alert(kvs...)).

func Debug

func Debug(kvs ...interface{}) *Emitter

Debug is equal to DefaultLogger.Debug(kvs...).

func Error

func Error(kvs ...interface{}) *Emitter

Error is equal to DefaultLogger.Error(kvs...).

func Fatal

func Fatal(kvs ...interface{}) *Emitter

Fatal is equal to DefaultLogger.Fatal(kvs...).

func Info

func Info(kvs ...interface{}) *Emitter

Info is equal to DefaultLogger.Info(kvs...).

func LevelLog added in v0.14.0

func LevelLog(level, depth int) *Emitter

LevelLog is equal to DefaultLogger.Level(level, depth).

func Panic added in v0.7.0

func Panic(kvs ...interface{}) *Emitter

Panic is equal to DefaultLogger.Panic(kvs...).

func Trace

func Trace(kvs ...interface{}) *Emitter

Trace is equal to DefaultLogger.Trace(kvs...).

func Warn

func Warn(kvs ...interface{}) *Emitter

Warn is equal to DefaultLogger.Warn(kvs...).

func (*Emitter) Bool added in v0.11.0

func (e *Emitter) Bool(key string, value bool) *Emitter

Bool is equal to e.Kv(key, value), but optimized for the value typed bool.

func (*Emitter) Duration added in v0.11.0

func (e *Emitter) Duration(key string, value time.Duration) *Emitter

Duration is equal to e.Kv(key, value), but optimized for the value typed time.Duration.

func (*Emitter) Enabled added in v0.10.0

func (e *Emitter) Enabled() bool

Enabled reports whether the log emitter is enabled.

func (*Emitter) Err added in v0.11.0

func (e *Emitter) Err(err error) *Emitter

Err is equal to e.Kv("err", err).

func (*Emitter) Float64 added in v0.11.0

func (e *Emitter) Float64(key string, value float64) *Emitter

Float64 is equal to e.Kv(key, value), but optimized for the value typed float64.

func (*Emitter) Int added in v0.11.0

func (e *Emitter) Int(key string, value int) *Emitter

Int is equal to e.Kv(key, value), but optimized for the value typed int.

func (*Emitter) Int64 added in v0.11.0

func (e *Emitter) Int64(key string, value int64) *Emitter

Int64 is equal to e.Kv(key, value), but optimized for the value typed int64.

func (*Emitter) Kv added in v0.10.0

func (e *Emitter) Kv(key string, value interface{}) *Emitter

Kv appends a key-value context into the log message and returns the emitter itself.

func (*Emitter) Kvs added in v0.10.0

func (e *Emitter) Kvs(kvs ...interface{}) *Emitter

Kvs appends a set of the key-value contexts into the log message, and returns the emitter itself.

func (*Emitter) Print added in v0.10.0

func (e *Emitter) Print(args ...interface{})

Print emits the log message to the underlying writer.

func (*Emitter) Printf added in v0.10.0

func (e *Emitter) Printf(msg string, args ...interface{})

Printf emits the log message to the underlying writer.

func (*Emitter) Str added in v0.11.0

func (e *Emitter) Str(key string, value string) *Emitter

Str is equal to e.Kv(key, value), but optimized for the value typed string.

func (*Emitter) StrSlice added in v0.12.0

func (e *Emitter) StrSlice(key string, value []string) *Emitter

StrSlice is equal to e.Kv(key, value), but optimized for the value typed []string.

func (*Emitter) Time added in v0.11.0

func (e *Emitter) Time(key string, value time.Time) *Emitter

Time is equal to e.Kv(key, value), but optimized for the value typed time.Time.

func (*Emitter) Uint added in v0.11.0

func (e *Emitter) Uint(key string, value uint) *Emitter

Uint is equal to e.Kv(key, value), but optimized for the value typed uint.

func (*Emitter) Uint64 added in v0.11.0

func (e *Emitter) Uint64(key string, value uint64) *Emitter

Uint64 is equal to e.Kv(key, value), but optimized for the value typed uint64.

type Encoder

type Encoder interface {
	// Start starts to encode the log record into the buffer dst.
	Start(dst []byte, loggerName, level string) []byte

	// Encode encodes the key-value with the stack depth into the buffer dst.
	Encode(dst []byte, key string, value interface{}) []byte

	// End ends to encode the log record with the message into the buffer dst.
	End(dst []byte, msg string) []byte
}

Encoder is used to encode the log record.

type Hook added in v0.7.0

type Hook interface {
	Run(e *Emitter, loggerName string, level int, depth int)
}

Hook is used to add the dynamic value into the log record.

func Caller

func Caller(key string) Hook

Caller returns a callback function that returns the caller like "File:FunctionName:Line".

type HookFunc added in v0.7.0

type HookFunc func(e *Emitter, name string, level int, depth int)

HookFunc is a function hook.

func (HookFunc) Run added in v0.7.0

func (f HookFunc) Run(e *Emitter, name string, level int, depth int)

Run implements the interface Hook.

type Logger

type Logger struct {
	*Output
	// contains filtered or unexported fields
}

Logger is the structured logger based on the key-value.

func Clone added in v0.7.0

func Clone() Logger

Clone is equal to DefaultLogger.Clone().

func New

func New(name string) Logger

New creates a new root logger, which encodes the log message as JSON and output the encoded log to os.Stderr.

func WithContext added in v0.10.0

func WithContext(key string, value interface{}) Logger

WithContext is equal to DefaultLogger.WithContext(key, value).

func WithContexts added in v0.10.0

func WithContexts(kvs ...interface{}) Logger

WithContexts is equal to DefaultLogger.WithContexts(kvs...).

func WithDepth

func WithDepth(depth int) Logger

WithDepth is equal to DefaultLogger.WithDepth(depth).

func WithHooks added in v0.10.0

func WithHooks(hooks ...Hook) Logger

WithHooks is equal to DefaultLogger.WithHooks(hooks...).

func WithLevel

func WithLevel(level int) Logger

WithLevel is equal to DefaultLogger.WithLevel(level).

func WithLevelFormat added in v0.14.0

func WithLevelFormat(format func(level int) string) Logger

WithLevelFormat is equal to DefaultLogger.WithLevelFormat(format).

func WithName

func WithName(name string) Logger

WithName is equal to DefaultLogger.New(name).

func (Logger) Alert added in v0.10.0

func (l Logger) Alert(kvs ...interface{}) *Emitter

Alert is equal to l.Level(LvlAlert, 0).Kvs(kvs...).

func (Logger) Clone

func (l Logger) Clone() Logger

Clone clones itself and returns a new one.

func (Logger) Contexts added in v0.10.0

func (l Logger) Contexts() (kvs []interface{})

Contexts returns the key-value contexts.

func (Logger) Debug

func (l Logger) Debug(kvs ...interface{}) *Emitter

Debug is equal to l.Level(LvlDebug, 0).Kvs(kvs...).

func (Logger) Depth

func (l Logger) Depth() int

Depth returns the stack depth of the current logger.

func (Logger) Enabled added in v0.7.0

func (l Logger) Enabled(level int) bool

Enabled reports whether the given level is enabled.

func (Logger) Error

func (l Logger) Error(kvs ...interface{}) *Emitter

Error is equal to l.Level(LvlError, 0).Kvs(kvs...).

func (Logger) Fatal

func (l Logger) Fatal(kvs ...interface{}) *Emitter

Fatal is equal to l.Level(LvlFatal, 0).Kvs(kvs...).

func (Logger) FormatLevel added in v0.14.0

func (l Logger) FormatLevel(level int) string

FormatLevel formats the level to string.

func (Logger) GetLevel added in v0.4.0

func (l Logger) GetLevel() int

GetLevel returns the level of the current logger.

func (Logger) Hooks added in v0.10.0

func (l Logger) Hooks() []Hook

Hooks returns the hooks.

func (Logger) Info

func (l Logger) Info(kvs ...interface{}) *Emitter

Info is equal to l.Level(LvlInfo, 0).Kvs(kvs...).

func (Logger) Level

func (l Logger) Level(level, depth int) *Emitter

Level returns an emitter with the level and the stack depth to emit the log.

func (Logger) Log

func (l Logger) Log(level, depth int, msg string, keysAndValues ...interface{})

Log is convenient function to emit a log, which is equal to l.Level(level, 0).Kvs(keysAndValues...).Printf(msg).

func (Logger) Name

func (l Logger) Name() string

Name returns the name of the current logger.

func (Logger) Panic added in v0.10.0

func (l Logger) Panic(kvs ...interface{}) *Emitter

Panic is equal to l.Level(LvlPanic, 0).Kvs(kvs...).

func (Logger) Sampler added in v0.10.0

func (l Logger) Sampler() Sampler

Sampler returns the sampler.

If no sampler is set, return nil.

func (*Logger) SetLevel added in v0.4.0

func (l *Logger) SetLevel(level int)

SetLevel resets the level, which is not thread-safe.

func (*Logger) SetLevelFormat added in v0.14.0

func (l *Logger) SetLevelFormat(format func(level int) string)

SetLevelFormat resets the level formatter, which is not thread-safe.

If format is nil or not set, use FormatLevel instead.

func (Logger) StdLogger added in v0.13.0

func (l Logger) StdLogger(prefix string, level int) *log.Logger

StdLogger returns a new log.Logger based on the current logger engine with the prefix and level.

func (Logger) Trace

func (l Logger) Trace(kvs ...interface{}) *Emitter

Trace is equal to l.Level(LvlTrace, 0).Kvs(kvs...).

func (Logger) Warn

func (l Logger) Warn(kvs ...interface{}) *Emitter

Warn is equal to l.Level(LvlWarn, 0).Kvs(kvs...).

func (Logger) WithContext added in v0.10.0

func (l Logger) WithContext(key string, value interface{}) Logger

WithContext returns a new logger that appends the key-value context.

func (Logger) WithContexts added in v0.10.0

func (l Logger) WithContexts(kvs ...interface{}) Logger

WithContexts returns a new logger that appends a set of the key-value contexts.

func (Logger) WithDepth

func (l Logger) WithDepth(depth int) Logger

WithDepth returns a new logger with the depth of the stack out of the logger.

func (Logger) WithEncoder

func (l Logger) WithEncoder(encoder Encoder) Logger

WithEncoder returns a new logger with the new output created the new encoder and the original writer, which will also re-encode all the key-value contexts.

func (Logger) WithHooks added in v0.10.0

func (l Logger) WithHooks(hooks ...Hook) Logger

WithHooks returns a new logger with the hooks.

func (Logger) WithLevel

func (l Logger) WithLevel(level int) Logger

WithLevel returns a new logger with the level.

func (Logger) WithLevelFormat added in v0.14.0

func (l Logger) WithLevelFormat(format func(level int) string) Logger

WithLevelFormat returns a new logger with the customized level formatter.

If format is nil, use FormatLevel instead.

func (Logger) WithName

func (l Logger) WithName(name string) Logger

WithName returns a new logger with the name.

  • If name is empty, the name of the new logger is equal to l.name.
  • If both name and l.name are not empty, it is equal to l.Name()+"."+name.

func (Logger) WithSampler added in v0.10.0

func (l Logger) WithSampler(sampler Sampler) Logger

WithSampler returns a new logger with the sampler.

If the sampler is nil, it will cancel the sampler.

func (Logger) WithWriter added in v0.10.0

func (l Logger) WithWriter(writer io.Writer) Logger

WithWriter returns a new logger with the writer.

func (Logger) Write added in v0.10.0

func (l Logger) Write(p []byte) (n int, err error)

Write implements the interface io.Writer.

type Output added in v0.7.0

type Output struct {
	// contains filtered or unexported fields
}

Output is used to handle the log output.

func NewOutput added in v0.7.0

func NewOutput(w io.Writer, encoder Encoder) *Output

NewOutput returns a new log output.

If the encoder is nil, use JSONEncoder in the sub-package encoder by default.

func (*Output) GetEncoder added in v0.7.0

func (o *Output) GetEncoder() Encoder

GetEncoder returns the log encoder.

func (*Output) GetWriter added in v0.7.0

func (o *Output) GetWriter() io.Writer

GetWriter returns the log writer.

func (*Output) SetEncoder added in v0.7.0

func (o *Output) SetEncoder(enc Encoder)

SetEncoder resets the log encoder to enc.

func (*Output) SetWriter added in v0.7.0

func (o *Output) SetWriter(w io.Writer)

SetWriter resets the log writer to w.

func (*Output) Writer added in v0.13.0

func (o *Output) Writer() io.Writer

Writer is the alias of GetWriter.

type Sampler added in v0.7.0

type Sampler interface {
	// Sample reports whether the log message should be sampled.
	// If the log message should be sampled, return true. Or, return false,
	// that's, the log message will be discarded.
	Sample(loggerName string, level int) bool
}

Sampler is used to sample the log message.

type SamplerFunc added in v0.7.0

type SamplerFunc func(loggerName string, level int) bool

SamplerFunc is a function sampler.

func (SamplerFunc) Sample added in v0.7.0

func (f SamplerFunc) Sample(name string, lvl int) bool

Sample implements the interface Sampler.

type SwitchSampler added in v0.8.0

type SwitchSampler struct {
	// contains filtered or unexported fields
}

SwitchSampler is a sampler to switch the proxy sampler.

func NewSwitchSampler added in v0.8.0

func NewSwitchSampler(sampler Sampler) *SwitchSampler

NewSwitchSampler returns a new SwitchSampler with the wrapped sampler.

func (*SwitchSampler) Get added in v0.8.0

func (s *SwitchSampler) Get() Sampler

Get returns the sampler.

func (*SwitchSampler) Sample added in v0.8.0

func (s *SwitchSampler) Sample(name string, level int) bool

Sample implements the interface Sampler.

func (*SwitchSampler) Set added in v0.8.0

func (s *SwitchSampler) Set(sampler Sampler)

Set resets the sampler.

Directories

Path Synopsis
Package encoder provides the encoder to encode the log message.
Package encoder provides the encoder to encode the log message.
kvjson
Package kvjson is used to encode the json key-value pair.
Package kvjson is used to encode the json key-value pair.
Package writer provides some log writers.
Package writer provides some log writers.

Jump to

Keyboard shortcuts

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