klog

package module
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2019 License: Apache-2.0 Imports: 19 Imported by: 0

README

klog Build Status GoDoc License

Package klog provides an simple, flexible, extensible, powerful and structured logging tool based on the level, which has done the better balance between the flexibility and the performance. It is inspired by log15, logrus, go-kit, logger and log.

See the GoDoc.

API has been stable. The current is v1.x.

Prerequisite

Now klog requires Go 1.x.

Features

  • The better performance.
  • Lazy evaluation of expensive operations.
  • The memory allocation is based on stack, not heap.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Child loggers which inherit and add their own private context.
  • Built-in support for logging to files, syslog, and the network. See Writer.

Example

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.New().WithLevel(klog.LvlWarn).WithKv("key1", "value1")

	field1 := klog.Field{Key: "key2", Value: "value2"}
	field2 := klog.Field{Key: "key3", Value: "value3"}

	// Style 1:
	log.Info().K("key4", "value4").Print("don't output")
	log.Error(field1, field2).K("key4", "value4").Printf("will output %s", "placeholder")

	// Style 2:
	log.K("key4", "value4").Infof("don't output")
	log.F(field1, field2).K("key4", "value4").Errorf("will output %s", "placeholder")
	log.Warnf("output '%s' log", "WARN") // You can emit log directly without key-value pairs.

	// Output:
	// t=2019-05-24T09:31:27.2592259+08:00 lvl=ERROR key1=value1 key2=value2 key3=value3 key4=value4 msg=will output placeholder
	// t=2019-05-24T09:31:27.2712334+08:00 lvl=ERROR key1=value1 key2=value2 key3=value3 key4=value4 msg=will output placeholder
	// t=2019-05-24T09:31:27.2712334+08:00 lvl=WARN key1=value1 msg=output 'WARN' log
}

Notice: klog supplies two kinds of log styles, Log(Style 1) and LLog (Style 2).

Furthermore, klog has built in a global logger, Std, which is equal to klog.New(), and you can use it and its exported function. Suggestion: You should use these functions instead.

Style 1: F(), K(), Tracef(), Debugf(), Infof(), Warnf(), Errorf(), Panicf(), Fatalf(), or Lf(level).

Style 2: Trace(), Debug(), Info(), Warn(), Error(), Panic(), Fatal(), or L(level).

package main

import "github.com/xgfone/klog"

func main() {
	klog.Std = klog.Std.WithLevelString("warn")
	// Or
	// klog.SetLevelString("warn")

	// Style 1:
	klog.Info().K("key", "value").Msg("don't output")
	klog.Error().K("key", "value").Msgf("will output %s", "placeholder")

	// Style 2:
	klog.K("key", "value").Infof("don't output")
	klog.K("key", "value").Errorf("will output %s", "placeholder")
	klog.Warnf("output '%s' log", "WARN") // You can emit log directly without key-value pairs.

	// Output:
	// t=2019-05-24T09:46:50.9758631+08:00 lvl=ERROR key=value msg=will output placeholder
	// t=2019-05-24T09:46:50.9868622+08:00 lvl=ERROR key=value msg=will output placeholder
	// t=2019-05-24T09:46:50.9868622+08:00 lvl=WARN msg=output 'WARN' log
}
Inherit the context of the parent logger
package main

import "github.com/xgfone/klog"

func main() {
	parent := klog.New().WithKv("parent", 123)
	child := parent.WithKv("child", 456)
	child.Info().Msgf("hello %s", "world")

	// Output:
	// t=2019-05-22T16:14:56.3740242+08:00 lvl=INFO parent=123 child=456 msg=hello world
}
Encoder
type Encoder func(buf *Builder, r Record) error

This pakcage has implemented four kinds of encoders, NothingEncoder, TextEncoder, JSONEncoder and StdJSONEncoder. It will use TextEncoder by default, but you can set it to others.

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.New().WithEncoder(klog.JSONEncoder())
	log.Info().K("key1", "value1").K("key2", "value2").Msg("hello world")

	// Output:
	// {"t":"2019-05-22T16:19:03.2972646+08:00","lvl":"INFO","key1":"value1","key2":"value2","msg":"hello world"}
}
Writer
type Writer interface {
	io.Closer
	Write(level Level, data []byte) (n int, err error)
}

All implementing the interface Writer are a Writer.

There are some built-in writers, such as DiscardWriter, LevelWriter, SafeWriter, StreamWriter, MultiWriter, FailoverWriter, ReopenWriter, FileWriter, NetWriter, SyslogWriter andSyslogNetWriter. It also supplies a rotating-size file writer SizedRotatingFile.

package main

import (
	"fmt"

	"github.com/xgfone/klog"
)

func main() {
	file, err := klog.FileWriter("test.log", "100M", 100)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	log := klog.New(file)
	log.Info().K("key", "value").Msg("hello world")

	// Output to file test.log:
	// t=2019-05-22T16:34:09.0685161+08:00 lvl=INFO key=value msg=hello world
}

If you want to use SizedRotatingFile as the writer, NewSimpleLogger maybe is your better choice.

package main

import "github.com/xgfone/klog"

func main() {
	log, _ := klog.NewSimpleLogger("warn", "test.log", "100M", 100)

	log.Info().Print("don't output")
	log.Error().Printf("will output %s %s", "key", "value")

	// Output to test.log:
	// t=2019-05-23T17:20:45.0741975+08:00 lvl=ERROR msg=will output key value
}
Lazy evaluation
type Valuer func(Record) (v interface{})

If the type of a certain value is Valuer, the logger engine will call it to get the corresponding value firstly before calling the encoder. There are some built-in Valuer, such as Caller(), CallerStack(), LineNo(), LineNoAsInt(), FuncName(), FuncFullName(), FileName(), FileLongName() and Package().

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.Std.WithKv("caller", klog.Caller())
	log.Info().K("stack", klog.CallerStack()).Msg("hello world")
	// Or
	// klog.AddKv("caller", klog.Caller())
	// klog.Info().K("stack", klog.CallerStack()).Msg("hello world")

	// Output:
	// t=2019-05-22T16:41:03.1281272+08:00 lvl=INFO caller=main.go:7 stack=[main.go:7] msg=hello world
}
Hook
type Hook func(name string, level Level) bool

You can use the hook to filter or count logs. There are four built-in hooks, DisableLogger, EnableLogger, DisableLoggerFromEnv and EnableLoggerFromEnv.

package main

import "github.com/xgfone/klog"

func main() {
	klog.Std = klog.Std.WithHook(klog.EnableLoggerFromEnv("mod"))
	log := klog.Std.WithName("debug")
	log.Info().Msg("hello world")
	// Or
	// klog.SetHook(klog.EnableLoggerFromEnv("mod")).SetName("debug")
	// klog.Info().Msg("hello world")

	// $ go run main.go  # No output
	// $ mod=debug=1 go run main.go
	// t=2019-05-22T17:07:20.2504266+08:00 logger=debug lvl=INFO msg=hello world
}
Logger Manager

There is default global manager, DefaultManager, which manages and caches all the loggers. You can use GetLogger(name) to get the logger from the cache, or return a new one if there is not the logger.

debugLogger := klog.GetLogger("debug")
serverLogger := klog.GetLogger("server")
defaultLogger := klog.GetLogger("")

Performance

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

Test 1
MacBook Pro(Retina, 13-inch, Mid 2014)
Intel Core i5 2.6GHz
8GB DDR3 1600MHz
macOS Mojave
test ops ns/op bytes/op allocs/op
BenchmarkKlogLNothingEncoder-4 5000000 274 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLTextEncoder-4 3000000 556 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLJSONEncoder-4 3000000 530 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLStdJSONEncoder-4 1000000 2190 ns/op 1441 B/op 22 allocs/op
BenchmarkKlogFNothingEncoder-4 10000000 189 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFTextEncoder-4 3000000 457 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFJSONEncoder-4 3000000 513 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFStdJSONEncoder-4 1000000 2177 ns/op 1441 B/op 22 allocs/op
Test 2
Dell Vostro 3470
Intel Core i5-7400 3.0GHz
8GB DDR4 2666MHz
Windows 10
test ops ns/op bytes/op allocs/op
BenchmarkKlogLNothingEncoder-4 10000000 235 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLTextEncoder-4 5000000 331 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLJSONEncoder-4 3000000 448 ns/op 32 B/op 1 allocs/op
BenchmarkKlogLStdJSONEncoder-4 1000000 1239 ns/op 1454 B/op 22 allocs/op
BenchmarkKlogFNothingEncoder-4 10000000 162 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFTextEncoder-4 5000000 315 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFJSONEncoder-4 3000000 436 ns/op 32 B/op 1 allocs/op
BenchmarkKlogFStdJSONEncoder-4 1000000 1091 ns/op 1454 B/op 22 allocs/op

Notice:

  1. L and F respectively represents Log and LLog interface.
  2. The once memory allocation, 32 B/op and 1 allocs/op, is due to the slice type []Field.

Documentation

Overview

Package klog provides an simple, flexible, extensible, powerful and structured logging tool based on the level, which has done the better balance between the flexibility and the performance.

Features

  • The better performance.
  • Lazy evaluation of expensive operations.
  • The memory allocation is based on stack, not heap.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Child loggers which inherit and add their own private context.
  • Built-in support for logging to files, syslog, and the network. See `Writer`.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// FieldSize is the default capacity of []Field to be created in the pool.
	FieldSize = 16

	// BuilderSize is the default capacity of Builder to be created in the pool.
	BuilderSize = 1024
)
View Source
var DefaultManager = NewManager()

DefaultManager is the default global manager of the logger.

View Source
var Levels = map[Level]string{
	LvlTrace: "TRACE",
	LvlDebug: "DEBUG",
	LvlInfo:  "INFO",
	LvlWarn:  "WARN",
	LvlError: "ERROR",
	LvlPanic: "PANIC",
	LvlFatal: "FATAL",
}

Levels is the pre-defined level names, but you can reset and override them.

View Source
var Std = New()

Std is the default global Logger.

Functions

func AppendCleaner

func AppendCleaner(clean ...func())

AppendCleaner appends the clean functions, which will be called when emitting the FATAL log.

func Debugf added in v1.2.0

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

Debugf equal to `Std.Debugf(level, msg, args...)` to emit a DEBUG log.

func Ef added in v1.10.0

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

Ef is equal to Std.Ef(err, format, args...).

func Errorf added in v1.2.0

func Errorf(msg string, args ...interface{})

Errorf equal to `Std.Errorf(level, msg, args...)` to emit a ERROR log.

func Fatalf added in v1.2.0

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

Fatalf equal to `Std.Fatalf(level, msg, args...)` to emit a FATAL log.

func FromWriter

func FromWriter(w Writer) io.WriteCloser

FromWriter converts Writer to io.WriteCloser.

func Infof added in v1.2.0

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

Infof equal to `Std.Infof(level, msg, args...)` to emit a INFO log.

func IsEnabled added in v1.11.0

func IsEnabled(lvl Level) bool

IsEnabled is equal to Std.IsEnabled(lvl).

func Lf added in v1.2.0

func Lf(level Level, msg string, args ...interface{})

Lf is equal to `Std.Lf(level, msg, args...)` to emit a specified `level` log.

func Panicf added in v1.2.0

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

Panicf equal to `Std.Panicf(level, msg, args...)` to emit a PANIC log.

func ParseSize

func ParseSize(s string) (size int64, err error)

ParseSize parses the size string. The size maybe have a unit suffix, such as "123", "123M, 123G". Valid size units are "b", "B", "k", "K", "m", "M", "g", "G", "t", "T", "p", "P". The lower units are 1000x, and the upper units are 1024x.

Notice: "" will be considered as 0.

Example
m10, _ := ParseSize("100M")
g10, _ := ParseSize("10g")

fmt.Println(m10)
fmt.Println(g10)
Output:

104857600
10000000000

func Tracef added in v1.2.0

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

Tracef equal to `Std.Tracef(level, msg, args...)` to emit a TRACE log.

func Warnf added in v1.2.0

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

Warnf equal to `Std.Warnf(level, msg, args...)` to emit a WARN log.

Types

type Builder

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

Builder is a thin wrapper around a byte slice. It's intended to be pooled, so the only way to construct one is via a Pool.

func NewBuilder

func NewBuilder(n int) *Builder

NewBuilder returns a new Builder with a initial capacity n.

func NewBuilderBytes

func NewBuilderBytes(buf []byte) *Builder

NewBuilderBytes returns a new Builder with a initial data.

func NewBuilderString

func NewBuilderString(s string) *Builder

NewBuilderString returns a new Builder with a initial string.

func (*Builder) AppendAny

func (b *Builder) AppendAny(any interface{}) (ok bool, err error)

AppendAny appends any value to the underlying buffer.

It supports the type:

nil     ==> "<nil>"
bool    ==> "true" or "false"
[]byte
string
float32
float64
int
int8
int16
int32
int64
uint
uint8
uint16
uint32
uint64
time.Time ==> time.RFC3339Nano
Slice
Map
interface error
interface io.WriterTo
interface fmt.Stringer
interface encoding.TextMarshaler

For the unknown type, it does not append it and return false, or return true.

Notice: for map[string]interface{} and map[string]string, they are optimized, so the order that the key-value is output is not determined.

func (*Builder) AppendAnyFmt added in v1.4.0

func (b *Builder) AppendAnyFmt(any interface{}) error

AppendAnyFmt is the same as AppendAny(any), but it will use `fmt.Sprintf("%+v", any)` to format the unknown type `any`.

func (*Builder) AppendBool

func (b *Builder) AppendBool(v bool)

AppendBool appends a bool to the underlying buffer.

func (*Builder) AppendByte

func (b *Builder) AppendByte(c byte)

AppendByte is the same as WriteByte, but no return.

func (*Builder) AppendFloat

func (b *Builder) AppendFloat(f float64, bitSize int)

AppendFloat appends a float to the underlying buffer. It doesn't quote NaN or +/- Inf.

func (*Builder) AppendInt

func (b *Builder) AppendInt(i int64)

AppendInt appends an integer to the underlying buffer (assuming base 10).

func (*Builder) AppendJSON

func (b *Builder) AppendJSON(value interface{}) error

AppendJSON appends the value as the JSON value, that's, the value will be encoded to JSON and appended into the underlying byte slice.

func (*Builder) AppendJSONString

func (b *Builder) AppendJSONString(s string)

AppendJSONString appends a string as JSON string, which will escape the double quotation(") and enclose it with a pair of the double quotation.

func (*Builder) AppendString

func (b *Builder) AppendString(s string)

AppendString is the same as WriteString, but no return.

func (*Builder) AppendTime

func (b *Builder) AppendTime(t time.Time, layout string)

AppendTime appends a time to the underlying buffer.

func (*Builder) AppendUint

func (b *Builder) AppendUint(i uint64)

AppendUint appends an unsigned integer to the underlying buffer (assuming base 10).

func (*Builder) Bytes

func (b *Builder) Bytes() []byte

Bytes returns a mutable reference to the underlying byte slice.

func (*Builder) Cap

func (b *Builder) Cap() int

Cap returns the capacity of the underlying byte slice.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the length of the underlying byte slice.

func (*Builder) Reset

func (b *Builder) Reset()

Reset resets the underlying byte slice.

Subsequent writes will re-use the slice's backing array.

func (*Builder) ResetBytes

func (b *Builder) ResetBytes(bs []byte)

ResetBytes resets the underlying byte slice to bs.

func (*Builder) String

func (b *Builder) String() string

String returns a string copy of the underlying byte slice.

func (*Builder) TrimNewline

func (b *Builder) TrimNewline()

TrimNewline trims any final "\n" byte from the end of the buffer.

func (*Builder) TruncateAfter

func (b *Builder) TruncateAfter(n int)

TruncateAfter truncates and discards last n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) TruncateBefore

func (b *Builder) TruncateBefore(n int)

TruncateBefore truncates and discards first n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) Write

func (b *Builder) Write(bs []byte) (int, error)

Write implements io.Writer.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) error

WriteByte writes a byte into the builder.

func (*Builder) WriteRune

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune writes a rune into the builder.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) (int, error)

WriteString writes a string into the builder.

func (*Builder) WriteTo

func (b *Builder) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type Encoder

type Encoder func(buf *Builder, r Record)

Encoder is the encoder of the log record.

Notice: w is the buffer writer.

func JSONEncoder

func JSONEncoder() Encoder

JSONEncoder encodes the key-values log as json.

Notice: the key name of the level is "lvl" and that of the time is "t" with time.RFC3339Nano, and that of the message is "msg". If the logger name exists, it will encode it and the key name is "logger".

Notice: it will ignore the empty msg.

func NothingEncoder

func NothingEncoder() Encoder

NothingEncoder encodes nothing.

func StdJSONEncoder

func StdJSONEncoder() Encoder

StdJSONEncoder is equal to JSONEncoder, which uses json.Marshal() to encode it, but the performance is a little bad.

Notice: it will ignore the empty msg.

func TextEncoder

func TextEncoder(quote ...bool) Encoder

TextEncoder encodes the key-values log as the text.

Notice: the key name of the level is "lvl", that of the time is "t" with time.RFC3339Nano, and that of the message is "msg". If the logger name exists, it will encode it and the key name is "logger".

If quote is true and the string value contains the space, it will be surrounded by a pair of the double quotation marks.

Notice: it will ignore the empty msg.

type Errors added in v1.1.0

type Errors []error

Errors is used to wrap more than one error.

func (Errors) Error added in v1.1.0

func (es Errors) Error() string

func (Errors) WriteTo added in v1.1.0

func (es Errors) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriteTo.

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field represents a key-value pair.

func NewErrField added in v1.10.0

func NewErrField(err error) Field

NewErrField returns a Field with the key "err" and the value err.

type FmtLogger

type FmtLogger interface {
	Writer() io.Writer

	Trace(format string, args ...interface{})
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
	Panic(format string, args ...interface{})
	Fatal(format string, args ...interface{})
}

FmtLogger represents a logger based on the % foramtter.

func ToFmtLogger

func ToFmtLogger(logger Logger) FmtLogger

ToFmtLogger converts Logger to FmtLogger.

type FmtLoggerError

type FmtLoggerError interface {
	Writer() io.Writer

	Trace(format string, args ...interface{}) error
	Debug(format string, args ...interface{}) error
	Info(format string, args ...interface{}) error
	Warn(format string, args ...interface{}) error
	Error(format string, args ...interface{}) error
	Panic(format string, args ...interface{}) error
	Fatal(format string, args ...interface{}) error
}

FmtLoggerError represents a logger based on the % foramtter.

func ToFmtLoggerError

func ToFmtLoggerError(logger Logger) FmtLoggerError

ToFmtLoggerError converts Logger to FmtLoggerError.

type FmtLoggerf added in v1.2.0

type FmtLoggerf interface {
	Writer() io.Writer

	Tracef(format string, args ...interface{})
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Panicf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

FmtLoggerf represents a logger based on the % foramtter.

func ToFmtLoggerf added in v1.2.0

func ToFmtLoggerf(logger Logger) FmtLoggerf

ToFmtLoggerf converts Logger to FmtLoggerf.

type Hook

type Hook func(name string, level Level) bool

Hook is a log hook, which receives the logger name and the log level and reports whether the log should continue to be emitted.

Notice: You can use it to sample the log.

func DisableLogger

func DisableLogger(names ...string) Hook

DisableLogger disables the logger, whose name is in names, to emit the log.

func DisableLoggerFromEnv

func DisableLoggerFromEnv(environ string) Hook

DisableLoggerFromEnv is the same as DisableLogger, but get the names from the environ.

The environ format is "environ=value", and `value` is like "name=off|0[,name=off|0]*". So, for `DisableLoggerFromEnv("mod")`, the environ variable

mod=n1=0,n2=off,n3=on,n4=1

the loggers named "n1" and "n2" will be disabled, and others, including "n3" and "n4", will be enabled.

func EnableLogger

func EnableLogger(names ...string) Hook

EnableLogger allows the logger, whose name is in names, to emit the log.

func EnableLoggerFromEnv

func EnableLoggerFromEnv(environ string) Hook

EnableLoggerFromEnv is the same as EnableLogger, but get the names from the environ.

The environ format is "environ=value", and `value` is like "name=on|1[,name=on|1]*". So, for `EnableLoggerFromEnv("mod")`, the environ variable

mod=n1=0,n2=off,n3=on,n4=1

the loggers named "n3" and "n4" will be enabled, and others, including "n1" and "n2", will be disabled.

type KV added in v1.5.0

type KV interface {
	Key() string
	Value() interface{}
}

KV represents a key-value interface.

type KvLogger added in v1.12.0

type KvLogger interface {
	Writer() io.Writer

	Tracef(msg string, kvs ...interface{})
	Debugf(msg string, kvs ...interface{})
	Infof(msg string, kvs ...interface{})
	Warnf(msg string, kvs ...interface{})
	Errorf(msg string, kvs ...interface{})
	Panicf(msg string, kvs ...interface{})
	Fatalf(msg string, kvs ...interface{})
}

KvLogger is a key-value logger interface.

Example
logger := ToKvLogger(Std.WithWriter(DiscardWriter()))
logger.Infof("test kv logger", "key1", "value1", "key2", "value2", "key3", 123)
// t=2019-10-19T16:16:31.336054+08:00 lvl=INFO key1=value1 key2=value2 key3=123 msg="test kv logger"
Output:

func ToKvLogger added in v1.12.0

func ToKvLogger(logger Logger) KvLogger

ToKvLogger converts the Logger to KvLogger.

type LLog added in v1.2.0

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

LLog is another interface of the key-value log with the level, which has implemented the KvLogger and FmtLoggerf interface.

func E added in v1.3.0

func E(err error) LLog

E is equal to Std.F(NewErrField(err)).

func F added in v1.2.0

func F(fields ...Field) LLog

F is equal to Std.F(fields...).

func K added in v1.2.0

func K(key string, value interface{}) LLog

K is equal to Std.K(key, value).

func V added in v1.5.0

func V(kvs ...KV) LLog

V is equal to Std.V(kvs...).

func (LLog) AddDepth added in v1.10.0

func (l LLog) AddDepth(depth int) LLog

AddDepth adds the depth.

func (LLog) Clone added in v1.12.0

func (l LLog) Clone() LLog

Clone clones itself to a new.

func (LLog) Debugf added in v1.2.0

func (l LLog) Debugf(msg string, args ...interface{})

Debugf emits a DEBUG log.

func (LLog) E added in v1.3.0

func (l LLog) E(err error) LLog

E is equal to l.F(NewErrField(err)).

func (LLog) Ef added in v1.10.0

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

Ef is short for l.E(err).Errorf(format, args...). If err is nil, however, it is eqaul to l.Infof(format, args...).

func (LLog) Errorf added in v1.2.0

func (l LLog) Errorf(msg string, args ...interface{})

Errorf emits a ERROR log.

func (LLog) F added in v1.2.0

func (l LLog) F(fields ...Field) LLog

F appends more than one key-value pair into the structured log by the field.

func (LLog) Fatalf added in v1.2.0

func (l LLog) Fatalf(msg string, args ...interface{})

Fatalf emits a FATAL log.

func (LLog) Infof added in v1.2.0

func (l LLog) Infof(msg string, args ...interface{})

Infof emits a INFO log.

func (LLog) IsEnabled added in v1.11.0

func (l LLog) IsEnabled(lvl Level) bool

IsEnabled reports whether the log with the lvl level can be logged.

func (LLog) K added in v1.2.0

func (l LLog) K(key string, value interface{}) LLog

K appends the key-value pair into the structured log.

func (LLog) Levelf added in v1.2.0

func (l LLog) Levelf(lvl Level, msg string, args ...interface{})

Levelf emits a customized level log.

func (LLog) Lf added in v1.2.0

func (l LLog) Lf(lvl Level, msg string, args ...interface{})

Lf is short for Level().

func (LLog) Panicf added in v1.2.0

func (l LLog) Panicf(msg string, args ...interface{})

Panicf emits a PANIC log.

func (LLog) Tracef added in v1.2.0

func (l LLog) Tracef(msg string, args ...interface{})

Tracef emits a TRACE log.

func (LLog) V added in v1.5.0

func (l LLog) V(kvs ...KV) LLog

V is equal to F, which will convert the type KV to Field.

func (LLog) Warnf added in v1.2.0

func (l LLog) Warnf(msg string, args ...interface{})

Warnf emits a WARN log.

func (LLog) Writer added in v1.12.0

func (l LLog) Writer() io.Writer

Writer returns the underlying io.Writer.

type Level

type Level int32

Level represents a level. The bigger the value, the higher the level.

const (
	LvlTrace Level = iota * 100
	LvlDebug
	LvlInfo
	LvlWarn
	LvlError
	LvlPanic
	LvlFatal
)

Predefine some levels.

You can define yourself level.

For LvlFatal or higher, it will emit the log and call the clean functions firstly, then the program will exit by calling `os.Exit(1)`.

For LvlPanic or higher, it will emit the log firstly, then panic with Record, but the field Fields is reset to nil.

func NameToLevel

func NameToLevel(name string, defaultPanic ...bool) Level

NameToLevel returns the Level by the name, which is case Insensitive.

If not panic, it will return `LvlInfo` instead if no level named `name`.

func (Level) MarshalJSON

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Level) String

func (l Level) String() string

func (Level) WriteTo

func (l Level) WriteTo(out io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type Log

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

Log is used to emit a structured key-value log.

func Debug

func Debug(fields ...Field) Log

Debug is equal to `Std.Debug(fields...)` to emit a DEBUG log.

func Error

func Error(fields ...Field) Log

Error is equal to `Std.Error(fields...)` to emit a ERROR log.

func Fatal

func Fatal(fields ...Field) Log

Fatal is equal to `Std.Fatal(fields...)` to emit a FATAL log.

func Info

func Info(fields ...Field) Log

Info is equal to `Std.Info(fields...)` to emit a INFO log.

func L

func L(level Level, fields ...Field) Log

L is equal to `Std.L(level, fields...)` to emit a specified `level` log.

func Panic

func Panic(fields ...Field) Log

Panic is equal to `Std.Panic(fields...)` to emit a PANIC log.

func Trace

func Trace(fields ...Field) Log

Trace is equal to `Std.Trace(fields...)` to emit a TRACE log.

func Warn

func Warn(fields ...Field) Log

Warn is equal to `Std.Warn(fields...)` to emit a WARN log.

func (Log) AddDepth added in v1.10.0

func (l Log) AddDepth(depth int) Log

AddDepth adds the depth.

func (Log) Clone added in v1.12.0

func (l Log) Clone() Log

Clone clones itself to a new.

func (Log) E added in v1.3.0

func (l Log) E(err error) Log

E is equal to l.F(NewErrField(err)).

func (Log) Ef added in v1.10.0

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

Ef is short for l.E(err).Msgf(format, args...).

func (Log) F

func (l Log) F(fields ...Field) Log

F appends more than one key-value pair into the structured log by the field.

func (Log) K

func (l Log) K(key string, value interface{}) Log

K appends the key-value pair into the structured log.

func (Log) Msg

func (l Log) Msg(args ...interface{})

Msg appends the msg into the structured log with the key "msg" at last.

Notice: "args" will be formatted by `fmt.Sprint(args...)`.

func (Log) Msgf

func (l Log) Msgf(format string, args ...interface{})

Msgf appends the msg into the structured log with the key "msg" at last.

Notice: "format" and "args" will be foramtted by `fmt.Sprintf(format, args...)`.

func (Log) Print

func (l Log) Print(args ...interface{})

Print is equal to l.Msg(args...).

func (Log) Printf

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

Printf is equal to l.Msgf(format, args...).

func (Log) V added in v1.5.0

func (l Log) V(kvs ...KV) Log

V is equal to F, which will convert the type KV to Field.

type Logger

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

Logger is a structured logger based on key-value.

func AddDepth added in v1.7.0

func AddDepth(depth int) *Logger

AddDepth is equal to Std.AddDepthSelf(depth).

func AddField added in v1.7.0

func AddField(fields ...Field) *Logger

AddField is equal to Std.AddField(fields...).

func AddHook added in v1.7.0

func AddHook(hooks ...Hook) *Logger

AddHook is equal to Std.AddHook(hooks...).

func AddKv added in v1.7.0

func AddKv(key string, value interface{}) *Logger

AddKv is equal to Std.AddKv(key, value).

func GetLogger added in v1.7.0

func GetLogger(name string) *Logger

GetLogger is equal to DefaultManager.GetLogger(name).

func New

func New(w ...Writer) Logger

New returns a new Logger with the writer w that is os.Stdout by default.

The default level is `LvlDebug`, and the default encoder is `TextEncoder()`.

func NewSimpleLogger

func NewSimpleLogger(level, filePath, fileSize string, fileNum int) (Logger, error)

NewSimpleLogger returns a new Logger based on the file writer by using `SizedRotatingFile`.

If filePath is "", it will ignore fileSize and fileNum, and use os.Stdout as the writer. If fileSize is "", it is "100M" by default. And fileNum is 100 by default.

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

func SetDepth added in v1.8.0

func SetDepth(depth int) *Logger

SetDepth is equal to Std.SetDepth(depth).

func SetEncoder added in v1.7.0

func SetEncoder(encoder Encoder) *Logger

SetEncoder is equal to Std.SetEncoder(encoder).

func SetLevel added in v1.7.0

func SetLevel(level Level) *Logger

SetLevel is equal to Std.SetLevel(level).

func SetLevelString added in v1.9.0

func SetLevelString(level string) *Logger

SetLevelString is equal to Std.SetLevelString(level).

func SetName added in v1.7.0

func SetName(name string) *Logger

SetName is equal to Std.SetName(name).

func SetWriter added in v1.7.0

func SetWriter(w Writer) *Logger

SetWriter is equal to Std.SetWriter(w).

func (Logger) AddDepth added in v1.2.0

func (l Logger) AddDepth(depth int) Logger

AddDepth is the same as WithDepth(depth), but it will grow it with depth, not reset it to depth.

func (*Logger) AddDepthSelf added in v1.7.0

func (l *Logger) AddDepthSelf(depth int) *Logger

AddDepthSelf increases the depth of the caller of the logger and returns itself for chaining call.

func (*Logger) AddField added in v1.7.0

func (l *Logger) AddField(fields ...Field) *Logger

AddField adds the fields of the logger and returns itself for chaining call.

func (*Logger) AddHook added in v1.7.0

func (l *Logger) AddHook(hooks ...Hook) *Logger

AddHook adds the hooks of the logger and returns itself for chaining call.

func (*Logger) AddKv added in v1.7.0

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

AddKv adds the key-value as the field context, which is equal to

l.AddField(Field{Key: key, Value: value})

It returns itself for chaining call.

func (Logger) Debug

func (l Logger) Debug(fields ...Field) Log

Debug is equal to l.Level(LvlDebug, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Debugf added in v1.2.0

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

Debugf emits a DEBUG log, which is equal to l.Levelf(LvlDebug, msg, args...).

func (Logger) E added in v1.3.0

func (l Logger) E(err error) LLog

E is equal to l.F(NewErrField(err)).

Notice: you must continue to call the level method, such as Levelf(), Debugf(), Infof(), Errorf(), etc, to trigger it.

func (Logger) Ef added in v1.10.0

func (l Logger) Ef(err error, msg string, args ...interface{})

Ef is equal to l.E(err).Errorf(msg, args...). If err is nil, however, it is eqaul to l.Infof(msg, args...).

func (Logger) Error

func (l Logger) Error(fields ...Field) Log

Error is equal to l.Level(LvlError, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Errorf added in v1.2.0

func (l Logger) Errorf(msg string, args ...interface{})

Errorf emits a ERROR log, which is equal to l.Levelf(LvlError, msg, args...).

func (Logger) F added in v1.2.0

func (l Logger) F(fields ...Field) LLog

F appends a key-value field log and returns another log interface to emit the level log.

Notice: you must continue to call the level method, such as Levelf(), Debugf(), Infof(), Errorf(), etc, to trigger it.

func (Logger) Fatal

func (l Logger) Fatal(fields ...Field) Log

Fatal is equal to l.Level(LvlFatal, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Fatalf added in v1.2.0

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

Fatalf emits a FATAL log, which is equal to l.Levelf(LvlFatal, msg, args...).

func (Logger) GetDepth

func (l Logger) GetDepth() int

GetDepth returns the depth of the caller stack.

func (Logger) GetEncoder added in v1.10.0

func (l Logger) GetEncoder() Encoder

GetEncoder returns the encoder of the logger.

func (Logger) GetHooks added in v1.10.0

func (l Logger) GetHooks() []Hook

GetHooks returns the hooks of the logger.

func (Logger) GetLevel

func (l Logger) GetLevel() Level

GetLevel returns the level of the logger.

func (Logger) GetName

func (l Logger) GetName() string

GetName returns the name of the logger.

func (Logger) GetWriter

func (l Logger) GetWriter() Writer

GetWriter returns the writer of the logger.

func (Logger) Info

func (l Logger) Info(fields ...Field) Log

Info is equal to l.Level(LvlInfo, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Infof added in v1.2.0

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

Infof emits a INFO log, which is equal to l.Levelf(LvlInfo, msg, args...).

func (Logger) IsEnabled added in v1.11.0

func (l Logger) IsEnabled(lvl Level) bool

IsEnabled reports whether the log with the lvl level can be logged.

func (Logger) K added in v1.2.0

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

K is equal to l.F(Field{Key: key, Value: value}).

Notice: you must continue to call the level method, such as Levelf(), Debugf(), Infof(), Errorf(), etc, to trigger it.

func (Logger) L

func (l Logger) L(level Level, fields ...Field) Log

L is short for Level(level, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Level

func (l Logger) Level(level Level, fields ...Field) Log

Level emits a specified `level` log.

You can gives some key-value field contexts optionally, which is equal to call `Log.F(fields...)`.

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Levelf added in v1.2.0

func (l Logger) Levelf(level Level, msg string, args ...interface{})

Levelf emits a specified `level` log, which is equal to l.F().Levelf(level, msg, args...).

func (Logger) Lf added in v1.2.0

func (l Logger) Lf(level Level, msg string, args ...interface{})

Lf is short for l.Levelf(level, msg, args...).

func (Logger) Panic

func (l Logger) Panic(fields ...Field) Log

Panic is equal to l.Level(LvlPanic, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Panicf added in v1.2.0

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

Panicf emits a PANIC log, which is equal to l.Levelf(LvlPanic, msg, args...).

func (Logger) Printf added in v1.6.0

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

Printf is the alias of Infof.

func (*Logger) SetDepth added in v1.8.0

func (l *Logger) SetDepth(depth int) *Logger

SetDepth resets the depth of the caller of the logger and returns itself for chaining call.

func (*Logger) SetEncoder added in v1.7.0

func (l *Logger) SetEncoder(encoder Encoder) *Logger

SetEncoder resets the encoder of the logger and returns itself for chaining call.

func (*Logger) SetLevel added in v1.7.0

func (l *Logger) SetLevel(level Level) *Logger

SetLevel resets the level of the logger and returns itself for chaining call.

func (*Logger) SetLevelString added in v1.9.0

func (l *Logger) SetLevelString(level string) *Logger

SetLevelString is equal to l.SetLevel(NameToLevel(level)).

func (*Logger) SetName added in v1.7.0

func (l *Logger) SetName(name string) *Logger

SetName resets the name of the logger and returns itself for chaining call.

func (*Logger) SetWriter added in v1.7.0

func (l *Logger) SetWriter(w Writer) *Logger

SetWriter resets the writer of the logger and returns itself for chaining call.

func (Logger) ToWriter added in v1.10.0

func (l Logger) ToWriter(lvl Level) io.Writer

ToWriter converts the logger to io.Writer.

func (Logger) Trace

func (l Logger) Trace(fields ...Field) Log

Trace is equal to l.Level(LvlTrace, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Tracef added in v1.2.0

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

Tracef emits a TRACE log, which is equal to l.Levelf(LvlTrace, msg, args...).

func (Logger) V added in v1.5.0

func (l Logger) V(kvs ...KV) LLog

V is equal to F, which will convert the type KV to Field.

func (Logger) Warn

func (l Logger) Warn(fields ...Field) Log

Warn is equal to l.Level(LvlWarn, fields...).

Notice: you must continue to call Msg() or Msgf() to trigger it.

func (Logger) Warnf added in v1.2.0

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

Warnf emits a WARN log, which is equal to l.Levelf(LvlWarn, msg, args...).

func (Logger) WithDepth

func (l Logger) WithDepth(depth int) Logger

WithDepth returns a new Logger with the caller depth.

Notice: 0 stands for the stack where the caller is.

func (Logger) WithEncoder

func (l Logger) WithEncoder(encoder Encoder) Logger

WithEncoder returns a new Logger with the encoder.

func (Logger) WithField

func (l Logger) WithField(fields ...Field) Logger

WithField returns a new Logger with the new field context.

func (Logger) WithHook

func (l Logger) WithHook(hook ...Hook) Logger

WithHook returns a new Logger with the hook, which will append the hook.

func (Logger) WithKv

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

WithKv returns a new Logger with the new key-value context, which is equal to

l.WithField(Field{Key: key, Value: value})

func (Logger) WithLevel

func (l Logger) WithLevel(level Level) Logger

WithLevel returns a new Logger with the level.

func (Logger) WithLevelString added in v1.9.0

func (l Logger) WithLevelString(level string) Logger

WithLevelString is equal to l.WithLevel(NameToLevel(level)).

func (Logger) WithName

func (l Logger) WithName(name string) Logger

WithName returns a new Logger with the name.

func (Logger) WithWriter

func (l Logger) WithWriter(w Writer) Logger

WithWriter returns a new Logger with the writer w.

type Manager added in v1.7.0

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

Manager is used to manage a set of the loggers.

func NewManager added in v1.7.0

func NewManager() *Manager

NewManager returns a new Manager, which will add the global logger, Std, by default.

func (*Manager) AddDepth added in v1.7.0

func (m *Manager) AddDepth(depth int)

AddDepth adds the depth to all the loggers.

func (*Manager) AddField added in v1.7.0

func (m *Manager) AddField(fields ...Field)

AddField adds the fields to all the loggers.

func (*Manager) AddHook added in v1.7.0

func (m *Manager) AddHook(hooks ...Hook)

AddHook adds the hooks to all the loggers.

func (*Manager) AddKv added in v1.7.0

func (m *Manager) AddKv(key string, value interface{})

AddKv adds the key-value to all the loggers.

func (*Manager) GetLogger added in v1.7.0

func (m *Manager) GetLogger(name string) *Logger

GetLogger returns a Logger named name, which will clone a new one with the name by the global Logger, Std, if no this logger.

func (*Manager) SetDepth added in v1.8.0

func (m *Manager) SetDepth(depth int)

SetDepth resets the depth to all the loggers.

func (*Manager) SetEncoder added in v1.7.0

func (m *Manager) SetEncoder(encoder Encoder)

SetEncoder sets the encoder to all the loggers.

func (*Manager) SetLevel added in v1.7.0

func (m *Manager) SetLevel(level Level)

SetLevel sets the level to all the loggers.

func (*Manager) SetLevelString added in v1.9.0

func (m *Manager) SetLevelString(level string)

SetLevelString is equal to m.SetLevel(NameToLevel(level)).

func (*Manager) SetWriter added in v1.7.0

func (m *Manager) SetWriter(w Writer)

SetWriter sets the writer to all the loggers.

type Printfer added in v1.6.0

type Printfer interface {
	Printf(msg string, args ...interface{})
}

Printfer is a Printf interface.

func PrintfFunc added in v1.6.0

func PrintfFunc(f func(msg string, args ...interface{})) Printfer

PrintfFunc converts a function to Printfer.

type Record

type Record struct {
	Msg    string    // The log message
	Time   time.Time // The start time when to emit the log
	Name   string    // The logger name
	Depth  int       // The depth of the caller
	Level  Level     // The log level
	Fields []Field   // The key-value logs
}

Record represents a log record.

type SizedRotatingFile

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

SizedRotatingFile is a file rotating logging handler based on the size.

func NewSizedRotatingFile

func NewSizedRotatingFile(filename string, size, count int,
	mode ...os.FileMode) (*SizedRotatingFile, error)

NewSizedRotatingFile returns a new SizedRotatingFile.

It is thread-safe for concurrent writes.

The default permission of the log file is 0644.

func (*SizedRotatingFile) Close

func (f *SizedRotatingFile) Close() (err error)

Close implements io.Closer.

func (*SizedRotatingFile) Flush

func (f *SizedRotatingFile) Flush() error

Flush flushes the data to the underlying disk.

func (*SizedRotatingFile) Write

func (f *SizedRotatingFile) Write(data []byte) (n int, err error)

Write implements io.Writer.

type Valuer

type Valuer func(Record) (v interface{})

Valuer is used to represent a lazy value by calling a function.

func Caller

func Caller(fullPath ...bool) Valuer

Caller returns a Valuer that returns the caller "file:line".

If fullPath is true, the file is the full path but removing the GOPATH prefix.

func CallerStack

func CallerStack(fullPath ...bool) Valuer

CallerStack returns a Valuer returning the caller stack without runtime.

If fullPath is true, the file is the full path but removing the GOPATH prefix.

func FileLongName

func FileLongName() Valuer

FileLongName returns the long name of the file where the caller is in.

func FileName

func FileName() Valuer

FileName returns the short name of the file where the caller is in.

func FuncFullName

func FuncFullName() Valuer

FuncFullName returns the full name of the function where the caller is in.

func FuncName

func FuncName() Valuer

FuncName returns the name of the function where the caller is in.

func LineNo

func LineNo() Valuer

LineNo returns the line number of the caller as string.

func LineNoAsInt

func LineNoAsInt() Valuer

LineNoAsInt returns the line number of the caller.

Return 0 if the line is missing.

func Package

func Package() Valuer

Package returns the name of the package where the caller is in.

type Writer

type Writer interface {
	io.Closer
	Write(level Level, data []byte) (n int, err error)
}

Writer is the interface to write the log to the underlying storage.

func DiscardWriter

func DiscardWriter() Writer

DiscardWriter discards all the data.

func FailoverWriter

func FailoverWriter(outs ...Writer) Writer

FailoverWriter writes all log records to the first handler specified, but will failover and write to the second handler if the first handler has failed, and so on for all handlers specified.

For example, you might want to log to a network socket, but failover to writing to a file if the network fails, and then to standard out if the file write fails.

func FileWriter added in v1.9.0

func FileWriter(filename, filesize string, filenum int) (Writer, error)

FileWriter returns a writer based the file, which uses NewSizedRotatingFile to generate the file writer. If filename is "", however, it will return a os.Stdout 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 LevelWriter

func LevelWriter(lvl Level, w Writer) Writer

LevelWriter filters the logs whose level is less than lvl.

func MultiWriter

func MultiWriter(outs ...Writer) Writer

MultiWriter writes one data to more than one destination.

func NetWriter

func NetWriter(network, addr string) (Writer, error)

NetWriter opens a socket to the given address and writes the log over the connection.

Notice: it will be wrapped by SafeWriter, so it's thread-safe.

func ReopenWriter

func ReopenWriter(factory func() (w io.WriteCloser, reopen <-chan bool, err error)) Writer

ReopenWriter returns a writer that can be closed then re-opened, which is used for logrotate typically.

Notice: It's thread-safe.

func SafeWriter

func SafeWriter(w Writer) Writer

SafeWriter is guaranteed that only a single writing operation can proceed at a time.

The returned Writer supports io.Closer, which will be forwarded to w.Close().

It's necessary for thread-safe concurrent writes.

func StreamWriter

func StreamWriter(w io.Writer) Writer

StreamWriter converts io.Writer to Writer.

If w has implemented io.Closer, the returned writer will forward the Close calling to it. Or do nothing.

func SyslogNetWriter

func SyslogNetWriter(net, addr string, priority syslog.Priority, tag string) (Writer, error)

SyslogNetWriter opens a connection to a log daemon over the network and writes all logs to it.

func SyslogWriter

func SyslogWriter(priority syslog.Priority, tag string) (Writer, error)

SyslogWriter opens a connection to the system syslog daemon by calling syslog.New and writes all logs to it.

func WriterFunc

func WriterFunc(w func(Level, []byte) (int, error), close ...func() error) Writer

WriterFunc adapts a function with w to Writer.

If giving the close function, it will be called when closing the writer. Or do nothing.

Jump to

Keyboard shortcuts

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