klog

package module
v4.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2020 License: Apache-2.0 Imports: 20 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 and zerolog.

API has been stable. The current is v4.x and support Go 1.7+.

Features

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

klog supports two kinds of the logger interfaces:

// Logger is the Key-Value logger interface.
type Logger interface {
	Trace(msg string, fields ...Field)
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(mst string, fields ...Field)
}

// Loggerf is the format logger interface.
type Loggerf interface {
	Tracef(msgfmt string, args ...interface{})
	Debugf(msgfmt string, args ...interface{})
	Infof(msgfmt string, args ...interface{})
	Warnf(msgfmt string, args ...interface{})
	Errorf(msgfmt string, args ...interface{})
	Fatalf(msgfmt string, args ...interface{})
}

Example

package main

import (
	"os"

	"github.com/xgfone/klog/v4"
)

func main() {
	opts := []klog.EncoderOption{
		klog.Quote(),
		klog.EncodeTime("t"),
		klog.EncodeLevel("lvl"),
		klog.EncodeLogger("logger"),
	}

	log := klog.New("name").
		WithEncoder(klog.TextEncoder(klog.SafeWriter(klog.StreamWriter(os.Stdout)), opts...)).
		WithLevel(klog.LvlWarn).
		WithCtx(klog.Caller("caller"))

	log.Info("log msg", klog.F("key1", "value1"), klog.F("key2", "value2"))
	log.Error("log msg", klog.F("key1", "value1"), klog.F("key2", "value2"))

	// Output:
	// t=1601185933 logger=name lvl=ERROR caller=main.go:23 key1=value1 key2=value2 msg="log msg"
}

klog supplies the default global logger and some convenient functions based on the level:

// Emit the log with the fields.
func Trace(msg string, fields ...Field)
func Debug(msg string, fields ...Field)
func Info(msg string, fields ...Field)
func Warn(msg string, fields ...Field)
func Error(msg string, fields ...Field)
func Fatal(msg string, fields ...Field)

// Emit the log with the formatter.
func Printf(format string, args ...interface{})
func Tracef(format string, args ...interface{})
func Debugf(format string, args ...interface{})
func Infof(format string, args ...interface{})
func Warnf(format string, args ...interface{})
func Errorf(format string, args ...interface{})
func Fatalf(format string, args ...interface{})
func Ef(err error, format string, args ...interface{})

For example,

package main

import (
	"fmt"

	"github.com/xgfone/klog/v4"
)

func main() {
	// Initialize the default logger.
	klog.DefalutLogger = klog.WithLevel(klog.LvlWarn).WithCtx(klog.Caller("caller"))

	// Emit the log with the fields.
	klog.Info("msg", klog.F("key1", "value1"), klog.F("key2", "value2"))
	klog.Error("msg", klog.F("key1", "value1"), klog.F("key2", "value2"))

	// Emit the log with the formatter.
	klog.Infof("%s log msg", "infof")
	klog.Errorf("%s log msg", "errorf")
	klog.Ef(fmt.Errorf("error"), "%s log msg", "errorf")

	// Output:
	// t=2020-09-27T23:52:35.63282+08:00 lvl=ERROR caller=main.go:15 key1=value1 key2=value2 msg=msg
	// t=2020-09-27T23:52:35.64482+08:00 lvl=ERROR caller=main.go:19 msg="errorf log msg"
	// t=2020-09-27T23:52:35.64482+08:00 lvl=ERROR caller=main.go:20 err=error msg="errorf log msg"
}
Encoder
type Encoder interface {
	// Writer returns the writer.
	Writer() Writer

	// SetWriter resets the writer.
	SetWriter(Writer)

	// Encode encodes the log record and writes it into the writer.
	Encode(Record)
}

This pakcage has implemented four kinds of encoders, NothingEncoder, TextEncoder, JSONEncoder and LevelEncoder. It will use TextEncoder by default.

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

All implementing the interface Writer are a Writer.

There are some built-in writers, such as DiscardWriter, FailoverWriter, LevelWriter, NetWriter, SafeWriter, SplitWriter, StreamWriter, FileWriter. FileWriter uses SizedRotatingFile to write the log to the file rotated based on the size.

package main

import (
	"fmt"

	"github.com/xgfone/klog/v4"
)

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

	klog.DefalutLogger.Encoder.SetWriter(file)
	klog.Info("hello world", klog.F("key", "value"))

	// Output to file test.log:
	// t=2020-09-27T23:56:04.0691608+08:00 lvl=INFO key=value msg="hello world"
}
Lazy evaluation

Field supports the lazy evaluation, such as F("key", func() interface{} {return "value"}). And there are some built-in lazy Field, such as Caller(), CallerStack().

Performance

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

Dell Vostro 3470
Intel Core i5-7400 3.0GHz
8GB DDR4 2666MHz
Windows 10
Go 1.13.4

Benchmark Package:

Function ops ns/op bytes/opt allocs/op
BenchmarkKlogNothingEncoder-4 273, 440, 714 4 0 0
BenchmarkKlogTextEncoder-4 30, 770, 728 43 0 0
BenchmarkKlogJSONEncoder-4 41, 626, 033 27 0 0
BenchmarkKlogTextEncoder10CtxFields-4 10, 344, 880 149 0 0
BenchmarkKlogJSONEncoder10CtxFields-4 7, 692, 381 165 0 0

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.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Avoid to allocate the memory on heap as far as possible.
  • 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 (
    "fmt"

    "github.com/xgfone/klog/v4"
)

func main() {
    // Initialize the default logger.
    klog.DefalutLogger = klog.WithLevel(klog.LvlWarn).WithCtx(klog.Caller("caller"))

    // Emit the log with the fields.
    klog.Info("msg", klog.F("key1", "value1"), klog.F("key2", "value2"))
    klog.Error("msg", klog.F("key1", "value1"), klog.F("key2", "value2"))

    // Emit the log with the formatter.
    klog.Infof("%s log msg", "infof")
    klog.Errorf("%s log msg", "errorf")
    klog.Ef(fmt.Errorf("error"), "%s log msg", "errorf")

    // Output:
    // t=2020-09-27T23:52:35.63282+08:00 lvl=ERROR caller=main.go:15 key1=value1 key2=value2 msg=msg
    // t=2020-09-27T23:52:35.64482+08:00 lvl=ERROR caller=main.go:19 msg="errorf log msg"
    // t=2020-09-27T23:52:35.64482+08:00 lvl=ERROR caller=main.go:20 err=error msg="errorf log msg"
}

Index

Constants

This section is empty.

Variables

View Source
var BuilderSize = 256

BuilderSize is the default capacity of Builder to be created in the pool.

View Source
var CallOnExit []func()

CallOnExit will be called before calling os.Exit(1) for Fatal or Fatalf.

View Source
var DefalutLogger = New("")

DefalutLogger is the default global logger.

Functions

func Debug

func Debug(msg string, fields ...Field)

Debug is equal to DefalutLogger.Debug(msg, fields...).

func Debugf

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

Debugf is equal to DefalutLogger.Debugf(msg, args...).

func Ef

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

Ef is equal to DefalutLogger.Error(fmt.Sprintf(msg, args), E(err)).

func Error

func Error(msg string, fields ...Field)

Error is equal to DefalutLogger.Error(msg, fields...).

func Errorf

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

Errorf is equal to DefalutLogger.Errorf(msg, args...).

func Fatal

func Fatal(msg string, fields ...Field)

Fatal is equal to DefalutLogger.Fatal(msg, fields...).

func Fatalf

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

Fatalf is equal to DefalutLogger.Fatalf(msg, args...).

func FieldFunc

func FieldFunc(key string) func(value interface{}) Field

FieldFunc returns a higher-order function to create the field with the key.

func Info

func Info(msg string, fields ...Field)

Info is equal to DefalutLogger.Info(msg, fields...).

func Infof

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

Infof is equal to DefalutLogger.Infof(msg, args...).

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.

func Printf

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

Printf is equal to DefalutLogger.Infof(msg, args...).

func RegisterCallOnExit

func RegisterCallOnExit(f func())

RegisterCallOnExit adds the call function into CallOnExit.

func ToIOWriter

func ToIOWriter(w Writer, lvl ...Level) io.WriteCloser

ToIOWriter converts Writer to io.WriteCloser with the level.

lvl is LvlInfo by default, which is only useful when w is the writer like SyslogWriter. Or it should be ignored.

func Trace

func Trace(msg string, fields ...Field)

Trace is equal to DefalutLogger.Trace(msg, fields...).

func Tracef

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

Tracef is equal to DefalutLogger.Tracef(msg, args...).

func Warn

func Warn(msg string, fields ...Field)

Warn is equal to DefalutLogger.Warn(msg, fields...).

func Warnf

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

Warnf is equal to DefalutLogger.Warnf(msg, args...).

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

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 interface {
	// Writer returns the writer.
	Writer() Writer

	// SetWriter resets the writer.
	SetWriter(Writer)

	// Encode encodes the log record and writes it into the writer.
	Encode(Record)
}

Encoder is used to encode the log record and to write it into the writer.

func EncoderFunc

func EncoderFunc(w Writer, encode func(*Builder, Record)) Encoder

EncoderFunc converts a encode function to Encoder, which will encode the record into the builder then write the result into the writer.

func FixRecordEncoder

func FixRecordEncoder(encoder Encoder, fixRecord func(Record) Record) Encoder

FixRecordEncoder returns an new Encoder, which will fix the record then use the encoder to encode the record.

For example, you can use it to adjust the stack.

func JSONEncoder

func JSONEncoder(w Writer, options ...EncoderOption) Encoder

JSONEncoder encodes the key-values log as json.

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

Notice: it will ignore the empty msg.

func LevelEncoder

func LevelEncoder(lvl Level, enc Encoder) Encoder

LevelEncoder returns a new Encoder, which will filter the log record when the priority of the log record is lower than that of lvl.

func NothingEncoder

func NothingEncoder() Encoder

NothingEncoder encodes nothing.

func TextEncoder

func TextEncoder(w Writer, options ...EncoderOption) Encoder

TextEncoder encodes the key-values log as the text.

Notice: The message will use "msg" as the key.

type EncoderOption

type EncoderOption interface{}

EncoderOption represents the option of the encoder to set the encoder.

func EncodeLevel

func EncodeLevel(key string) EncoderOption

EncodeLevel enables the encoder to encode the level with the key.

func EncodeLogger

func EncodeLogger(key string) EncoderOption

EncodeLogger enables the encoder to encode the logger name with the key.

func EncodeTime

func EncodeTime(key string, format ...string) EncoderOption

EncodeTime enables the encoder to encode the time as the format with the key, which will encode the time as the integer second if format is missing.

func Newline

func Newline(newline bool) EncoderOption

Newline enables the encoder whether or not to append a newline.

It is true by default.

func Quote

func Quote() EncoderOption

Quote is used by TextEncoder, which will use a pair of double quotation marks to surround the string value if it contains the space.

type ExtLogger

type ExtLogger struct {
	Name    string
	Ctxs    []Field
	Depth   int
	Level   Level
	Encoder Encoder
}

ExtLogger is a extended logger implemented the Logger and Loggerf interface.

func New

func New(name string) *ExtLogger

New creates a new ExtLogger, which will use TextEncoder as the encoder and output the log to os.Stdout.

func NewSimpleLogger

func NewSimpleLogger(name, level, filePath, fileSize string, fileNum int) (*ExtLogger, error)

NewSimpleLogger returns a new simple logger.

func WithCtx

func WithCtx(fields ...Field) *ExtLogger

WithCtx is equal to DefalutLogger.WithCtx(fields...).

func WithDepth

func WithDepth(depth int) *ExtLogger

WithDepth is equal to DefalutLogger.WithDepth(depth).

func WithEncoder

func WithEncoder(enc Encoder) *ExtLogger

WithEncoder is equal to DefalutLogger.WithEncoder(enc).

func WithLevel

func WithLevel(level Level) *ExtLogger

WithLevel is equal to DefalutLogger.WithLevel(level).

func WithName

func WithName(name string) *ExtLogger

WithName is equal to DefalutLogger.WithName(name).

func (*ExtLogger) Clone

func (l *ExtLogger) Clone() *ExtLogger

Clone clones itself and returns a new one.

func (*ExtLogger) Debug

func (l *ExtLogger) Debug(msg string, fields ...Field)

Debug implements the interface Logger.

func (*ExtLogger) Debugf

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

Debugf implements the interface Loggerf.

func (*ExtLogger) Error

func (l *ExtLogger) Error(msg string, fields ...Field)

Error implements the interface Logger.

func (*ExtLogger) Errorf

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

Errorf implements the interface Loggerf.

func (*ExtLogger) Fatal

func (l *ExtLogger) Fatal(msg string, fields ...Field)

Fatal implements the interface Logger, but call the exit functions in CallOnExit before the program exits.

func (*ExtLogger) Fatalf

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

Fatalf implements the interface Loggerf, but call the exit functions in CallOnExit before the program exits.

func (*ExtLogger) Info

func (l *ExtLogger) Info(msg string, fields ...Field)

Info implements the interface Logger.

func (*ExtLogger) Infof

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

Infof implements the interface Loggerf.

func (*ExtLogger) Log

func (l *ExtLogger) Log(lvl Level, depth int, msg string, args []interface{}, fields []Field)

Log emits the logs with the level and the depth.

func (*ExtLogger) Printf

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

Printf is equal to l.Infof(msg, args...).

func (*ExtLogger) StdLog

func (l *ExtLogger) StdLog(prefix string, flags ...int) *log.Logger

StdLog converts the ExtLogger to the std log.

func (*ExtLogger) Trace

func (l *ExtLogger) Trace(msg string, fields ...Field)

Trace implements the interface Logger.

func (*ExtLogger) Tracef

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

Tracef implements the interface Loggerf.

func (*ExtLogger) Warn

func (l *ExtLogger) Warn(msg string, fields ...Field)

Warn implements the interface Logger.

func (*ExtLogger) Warnf

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

Warnf implements the interface Loggerf.

func (*ExtLogger) WithCtx

func (l *ExtLogger) WithCtx(ctxs ...Field) *ExtLogger

WithCtx returns a new ExtLogger with the new context fields.

func (*ExtLogger) WithDepth

func (l *ExtLogger) WithDepth(depth int) *ExtLogger

WithDepth returns a new ExtLogger, which will increase the depth.

func (*ExtLogger) WithEncoder

func (l *ExtLogger) WithEncoder(e Encoder) *ExtLogger

WithEncoder returns a new ExtLogger with the new encoder.

func (*ExtLogger) WithLevel

func (l *ExtLogger) WithLevel(level Level) *ExtLogger

WithLevel returns a new ExtLogger with the new level.

func (*ExtLogger) WithName

func (l *ExtLogger) WithName(name string) *ExtLogger

WithName returns a new ExtLogger with the new name.

type Field

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

Field represents a key-value pair.

func E

func E(err error) Field

E is equal to F("err", err).

func F

func F(key string, value interface{}) Field

F returns a new Field. If value is "func() interface{}" or "func() string", it will be evaluated when the log is emitted, that's, it is lazy.

type FieldBuilder added in v4.1.0

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

FieldBuilder is used to build a set of fields.

func FB added in v4.1.0

func FB(cap int) FieldBuilder

FB is the alias of NewFieldBuilder.

func NewFieldBuilder added in v4.1.0

func NewFieldBuilder(cap int) FieldBuilder

NewFieldBuilder returns a new FieldBuilder with the capacity of the fields.

func (FieldBuilder) E added in v4.1.0

func (fb FieldBuilder) E(err error) FieldBuilder

E appends the error field if err is not equal to nil.

func (FieldBuilder) F added in v4.1.0

func (fb FieldBuilder) F(key string, value interface{}) FieldBuilder

F is the alias of Field.

func (FieldBuilder) Field added in v4.1.0

func (fb FieldBuilder) Field(key string, value interface{}) FieldBuilder

Field appends the field with the key and value.

func (FieldBuilder) Fields added in v4.1.0

func (fb FieldBuilder) Fields() []Field

Fields returns the built fields.

func (FieldBuilder) Release added in v4.1.0

func (fb FieldBuilder) Release()

Release releases the fields into the pool.

func (*FieldBuilder) Reset added in v4.1.0

func (fb *FieldBuilder) Reset()

Reset resets the fields and reuses the underlying memory.

type FieldError added in v4.1.0

type FieldError interface {
	FieldReleaser
	error
}

FieldError is the error interface with some fields.

func FE added in v4.1.0

func FE(err error, fields FieldReleaser) FieldError

FE is the alias of NewFieldError.

func NewFieldError added in v4.1.0

func NewFieldError(err error, fields FieldReleaser) FieldError

NewFieldError returns a new FieldError.

type FieldReleaser added in v4.1.0

type FieldReleaser interface {
	Fields() []Field
	Release()
}

FieldReleaser is used to get and release the fields.

type Level

type Level uint8

Level is the level of the log.

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

Predefine some levels.

func NameToLevel

func NameToLevel(level string, defaultLevel ...Level) Level

NameToLevel returns a Level by the level name.

Support the level name, which is case insensitive:

TRACE
DEBUG
INFO
WARN
ERROR
FATAL

func (Level) String

func (l Level) String() string

type Logger

type Logger interface {
	Trace(msg string, fields ...Field)
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(mst string, fields ...Field) // Log and exit with the code 1.
}

Logger is an logger interface based on the key-value pairs to emit the log.

type Loggerf

type Loggerf interface {
	Tracef(msgfmt string, args ...interface{})
	Debugf(msgfmt string, args ...interface{})
	Infof(msgfmt string, args ...interface{})
	Warnf(msgfmt string, args ...interface{})
	Errorf(msgfmt string, args ...interface{})
	Fatalf(msgfmt string, args ...interface{}) // Log and exit with the code 1.
}

Loggerf is an logger interface based on the format string to emit the log.

type Record

type Record struct {
	Name  string    // The logger name, which may be empty
	Time  time.Time // The start time when to emit the log
	Depth int       // The stack depth of the caller

	Lvl    Level   // The log level
	Msg    string  // The log message
	Ctxs   []Field // The SHARED key-value contexts. DON'T MODIFY IT!
	Fields []Field // The key-value pairs
}

Record represents a log record.

type SizedRotatingFile

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

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

func NewSizedRotatingFile

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

NewSizedRotatingFile returns a new SizedRotatingFile, which is not thread-safe.

The default permission of the log file is 0644.

func (*SizedRotatingFile) Close

func (f *SizedRotatingFile) Close() 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 StackField

type StackField interface {
	Field
	Stack(depth int) interface{}
}

StackField is used to get the stack of the caller.

func Caller

func Caller(key string, fullPath ...bool) StackField

Caller returns a StackField 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(key string, fullPath ...bool) StackField

CallerStack returns a StackField returning the caller stack without runtime.

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

func StackFieldFunc

func StackFieldFunc(key string, getStack func(depth int) interface{}) StackField

StackFieldFunc returns a new StackField.

type Writer

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

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

func BufferWriter

func BufferWriter(w Writer, bufferSize int) Writer

BufferWriter returns a new Writer to write all logs to a buffer which flushes into the wrapped writer whenever it is available for writing.

func DiscardWriter

func DiscardWriter() Writer

DiscardWriter discards all the data.

func FailoverWriter

func FailoverWriter(writers ...Writer) Writer

FailoverWriter writes all log records to the first writer specified, but will failover and write to the second writer if the first writer has failed, and so on for all writers 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

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 NetWriter

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

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

func SafeWriter

func SafeWriter(w Writer) Writer

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

It's necessary for thread-safe concurrent writes.

func SplitWriter

func SplitWriter(getWriter func(Level) Writer) Writer

SplitWriter returns a level-separated writer, which will write the log record into the separated writer.

func StreamWriter

func StreamWriter(w io.Writer) Writer

StreamWriter converts io.Writer to Writer.

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(write func(Level, []byte) (int, error), close ...func() error) Writer

WriterFunc adapts the function to Writer.

Jump to

Keyboard shortcuts

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