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/v2" ) func main() { // Initialize the default logger. log := klog.WithLevel(klog.LvlWarn).WithCtx(klog.Caller("caller")) // if file, err := klog.FileWriter("file.log", "100M", 100); err == nil { // log.Encoder().SetWriter(file) // } else { // fmt.Println(err) // return // } klog.SetDefaultLogger(log) // Emit the log with the fields. klog.Info("msg", klog.F("k1", "v1"), klog.F("k2", "v2")) klog.Error("msg", klog.F("k1", "v1"), klog.F("k2", "v2")) // Emit the log with the formatter. klog.Infof("log %s", "msg") klog.Warnf("log %s", "msg") klog.Ef(fmt.Errorf("e"), "log %s", "msg") // Output: // t=2019-11-19T09:54:36.4956708+08:00 lvl=ERROR caller=main.go:22 k1=v1 k2=v2 msg=msg // t=2019-11-19T09:54:36.4973725+08:00 lvl=WARN caller=main.go:26 msg="log msg" // t=2019-11-19T09:54:36.4974311+08:00 lvl=ERROR caller=main.go:27 err=e msg="log msg" }
Index ¶
- Variables
- func Debug(msg string, fields ...Field)
- func Debugf(format string, args ...interface{})
- func Ef(err error, format string, args ...interface{})
- func Error(msg string, fields ...Field)
- func Errorf(format string, args ...interface{})
- func Fatal(msg string, fields ...Field)
- func Fatalf(format string, args ...interface{})
- func Info(msg string, fields ...Field)
- func Infof(format string, args ...interface{})
- func Log(level Level, msg string, fields ...Field)
- func NewStdLogger(w Writer, prefix string, flags ...int) *log.Logger
- func Panic(msg string, fields ...Field)
- func Panicf(format string, args ...interface{})
- func ParseSize(s string) (size int64, err error)
- func Printf(format string, args ...interface{})
- func RegisterCallOnExit(f func())
- func SetDefaultLogger(l ExtLogger)
- func SetEncoder(enc Encoder)
- func SetLevel(lvl Level)
- func Sprintf(msg string, args ...interface{}) string
- func ToIOWriter(w Writer) io.WriteCloser
- func Trace(msg string, fields ...Field)
- func Tracef(format string, args ...interface{})
- func UpdateDefaultLogger(level, filePath, fileSize string, fileNum int) error
- func Warn(msg string, fields ...Field)
- func Warnf(format string, args ...interface{})
- type Builder
- func (b *Builder) AppendAny(any interface{}) (ok bool, err error)
- func (b *Builder) AppendAnyFmt(any interface{}) error
- func (b *Builder) AppendBool(v bool)
- func (b *Builder) AppendByte(c byte)
- func (b *Builder) AppendFloat(f float64, bitSize int)
- func (b *Builder) AppendInt(i int64)
- func (b *Builder) AppendJSON(value interface{}) error
- func (b *Builder) AppendJSONString(s string)
- func (b *Builder) AppendString(s string)
- func (b *Builder) AppendTime(t time.Time, layout string)
- func (b *Builder) AppendUint(i uint64)
- func (b *Builder) Bytes() []byte
- func (b *Builder) Cap() int
- func (b *Builder) Len() int
- func (b *Builder) Reset()
- func (b *Builder) ResetBytes(bs []byte)
- func (b *Builder) String() string
- func (b *Builder) TrimNewline()
- func (b *Builder) TruncateAfter(n int)
- func (b *Builder) TruncateBefore(n int)
- func (b *Builder) Write(bs []byte) (int, error)
- func (b *Builder) WriteByte(c byte) error
- func (b *Builder) WriteRune(r rune) (int, error)
- func (b *Builder) WriteString(s string) (int, error)
- func (b *Builder) WriteTo(w io.Writer) (int64, error)
- type Encoder
- func EncoderFunc(w Writer, encode func(*Builder, Record)) Encoder
- func FixRecordEncoder(encoder Encoder, fixRecord func(Record) Record) Encoder
- func GetEncoder() Encoder
- func GetEncoderFromLogger(logger Logger, defaultEncoder ...Encoder) Encoder
- func JSONEncoder(w Writer, options ...EncoderOption) Encoder
- func LevelEncoder(lvl Level, enc Encoder) Encoder
- func NothingEncoder() Encoder
- func TextEncoder(w Writer, options ...EncoderOption) Encoder
- type EncoderOption
- type ExtLogger
- func GetDefaultLogger() ExtLogger
- func New(name string) ExtLogger
- func NewSimpleLogger(name, level, filePath, fileSize string, fileNum int) (ExtLogger, error)
- func WithCtx(fields ...Field) ExtLogger
- func WithDepth(depth int) ExtLogger
- func WithEncoder(enc Encoder) ExtLogger
- func WithLevel(level Level) ExtLogger
- func WithName(name string) ExtLogger
- type Field
- type FmtLogger
- type Level
- type LevelLogger
- type Logger
- type Printfer
- type Record
- type SizedRotatingFile
- type StackField
- type WriteCloser
- func SyslogNetWriter(net, addr string, priority syslog.Priority, tag string) (WriteCloser, error)
- func SyslogWriter(priority syslog.Priority, tag string) (WriteCloser, error)
- func ToWriteCloser(w Writer) WriteCloser
- func WriteCloserFunc(write func(Level, []byte) (int, error), close func() error) WriteCloser
- type WriteFlushCloser
- func BufferWriter(w Writer, bufferSize int) WriteFlushCloser
- func DiscardWriter() WriteFlushCloser
- func FailoverWriter(writers ...Writer) WriteFlushCloser
- func FileWriter(filename, filesize string, filenum int) (WriteFlushCloser, error)
- func FileWriterWithoutLock(filename, filesize string, filenum int) (WriteFlushCloser, error)
- func LevelWriter(lvl Level, w Writer) WriteFlushCloser
- func NetWriter(network, addr string) (WriteFlushCloser, error)
- func SafeWriter(w Writer) WriteFlushCloser
- func SplitWriter(getWriter func(Level) Writer, flush ...func() error) WriteFlushCloser
- func StreamWriter(w io.Writer) WriteFlushCloser
- func ToWriteFlushCloser(w Writer) WriteFlushCloser
- func WriteFlushCloserFunc(write func(Level, []byte) (int, error), flush, close func() error) WriteFlushCloser
- type Writer
Constants ¶
This section is empty.
Variables ¶
var ( LvlTrace = NewLevel("TRACE", 0) LvlDebug = NewLevel("DEBUG", 100) LvlInfo = NewLevel("INFO", 200) LvlWarn = NewLevel("WARN", 300) LvlError = NewLevel("ERROR", 400) LvlCrit = NewLevel("CRIT", 500) LvlEmerg = NewLevel("EMERG", 600) LvlMax = NewLevel("MAX", math.MaxInt32) )
Predefine some levels.
var BuilderSize = 256
BuilderSize is the default capacity of Builder to be created in the pool.
var CallOnExit []func()
CallOnExit will be called before calling os.Exit(1) for Fatal or Fatalf.
var Levels = map[string]Level{ "TRACE": LvlTrace, "DEBUG": LvlDebug, "INFO": LvlInfo, "WARN": LvlWarn, "ERROR": LvlError, "CRIT": LvlCrit, "EMERG": LvlEmerg, "MAX": LvlMax, }
Levels is a set of Level, which is used to get the level by the name.
Functions ¶
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf is equal to Log(LvlDebug, Sprintf(format, args...)).
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf is equal to Log(LvlError, Sprintf(format, args...)).
func Fatal ¶ added in v3.1.0
Fatal is equal to Log(LvlEmerg, msg, fields...), then call os.Exit(1) to exit.
func Fatalf ¶ added in v3.1.0
func Fatalf(format string, args ...interface{})
Fatalf is equal to Log(LvlEmerg, Sprintf(format, args...)), then call os.Exit(1) to exit.
func Infof ¶
func Infof(format string, args ...interface{})
Infof is equal to Log(LvlInfo, Sprintf(format, args...)).
func NewStdLogger ¶
NewStdLogger returns a new log.Logger with the writer.
If not giving flags, it is log.LstdFlags|log.Lmicroseconds|log.Lshortfile by default.
func Panicf ¶ added in v3.1.0
func Panicf(format string, args ...interface{})
Panicf is equal to Log(LvlCrit, Sprintf(format, args...)), then panic.
func ParseSize ¶
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(format string, args ...interface{})
Printf is equal to Infof(format, args...).
func RegisterCallOnExit ¶ added in v3.2.0
func RegisterCallOnExit(f func())
RegisterCallOnExit adds the call function into CallOnExit.
func SetDefaultLogger ¶
func SetDefaultLogger(l ExtLogger)
SetDefaultLogger sets the default logger to l.
func SetEncoder ¶
func SetEncoder(enc Encoder)
SetEncoder resets the encoder of the default logger, which is TextEncoder by default.
func SetLevel ¶
func SetLevel(lvl Level)
SetLevel resets the level of the default logger, which is LvlDebug by default.
func ToIOWriter ¶
func ToIOWriter(w Writer) io.WriteCloser
ToIOWriter converts Writer to io.WriteCloser.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef is equal to Log(LvlTrace, Sprintf(format, args...)).
func UpdateDefaultLogger ¶
UpdateDefaultLogger updates the default logger with NameToLevel(level) and FileWriter(filePath, fileSize, fileNum) if filePath is not "".
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 ¶
NewBuilder returns a new Builder with a initial capacity n.
func NewBuilderBytes ¶
NewBuilderBytes returns a new Builder with a initial data.
func NewBuilderString ¶
NewBuilderString returns a new Builder with a initial string.
func (*Builder) AppendAny ¶
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 ¶
AppendAnyFmt is the same as AppendAny(any), but it will use `fmt.Sprintf("%+v", any)` to format the unknown type `any`.
func (*Builder) AppendBool ¶
AppendBool appends a bool to the underlying buffer.
func (*Builder) AppendByte ¶
AppendByte is the same as WriteByte, but no return.
func (*Builder) AppendFloat ¶
AppendFloat appends a float to the underlying buffer. It doesn't quote NaN or +/- Inf.
func (*Builder) AppendInt ¶
AppendInt appends an integer to the underlying buffer (assuming base 10).
func (*Builder) AppendJSON ¶
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 ¶
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 ¶
AppendString is the same as WriteString, but no return.
func (*Builder) AppendTime ¶
AppendTime appends a time to the underlying buffer.
func (*Builder) AppendUint ¶
AppendUint appends an unsigned integer to the underlying buffer (assuming base 10).
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 ¶
ResetBytes resets the underlying byte slice to bs.
func (*Builder) TrimNewline ¶
func (b *Builder) TrimNewline()
TrimNewline trims any final "\n" byte from the end of the buffer.
func (*Builder) TruncateAfter ¶
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 ¶
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) WriteString ¶
WriteString writes a string into the builder.
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 ¶
EncoderFunc converts a encode function to Encoder, which will encode the record into the builder then write the result into the writer.
func FixRecordEncoder ¶
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 GetEncoderFromLogger ¶
GetEncoderFromLogger returns the encoder from logger if it has the method `func Encoder() Encoder`. Or, it will return defaultEncoder if given or nil.
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 ¶
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 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 interface { Logger SetLevel(level Level) // Reset the level SetEncoder(Encoder) // Reset the encoder Encoder() Encoder // Return the encoder of the logger WithCtx(fields ...Field) ExtLogger // Return a new Logger with the fields WithName(name string) ExtLogger // Return a new Logger with the new name WithLevel(level Level) ExtLogger // Return a new Logger with the level WithEncoder(e Encoder) ExtLogger // Return a new Logger with the encoder WithDepth(depth int) ExtLogger // Return a new Logger with the increased depth }
ExtLogger is a extended logger interface.
func GetDefaultLogger ¶
func GetDefaultLogger() ExtLogger
GetDefaultLogger returns the default logger.
func New ¶
New creates a new ExtLogger, which will use TextEncoder as the encoder and output the log to os.Stdout.
func NewSimpleLogger ¶
NewSimpleLogger returns a new simple logger.
func WithEncoder ¶
WithEncoder returns a new ExtLogger based on the default logger with the encoder.
type Field ¶
type Field interface { Key() string Value() interface{} }
Field represents a key-value pair.
type FmtLogger ¶
type FmtLogger interface { 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{}) }
FmtLogger is a formatter logger interface.
func ToFmtLogger ¶
ToFmtLogger converts ExtLogger to FmtLogger.
type Level ¶
type Level interface { // Priority returns the priority of the level. // The bigger the level, the higher the priority. Priority() int // String returns the name of the level. String() string }
Level represents the logger level.
func NameToLevel ¶
NameToLevel returns the Level by the name, which is case Insensitive.
If not panic, it will return `LvlInfo` instead if no level named `name`.
type LevelLogger ¶
type LevelLogger 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) }
LevelLogger is a convenient logger interface based on the level.
func ToLevelLogger ¶
func ToLevelLogger(logger ExtLogger) LevelLogger
ToLevelLogger converts ExtLogger to LevelLogger.
type Printfer ¶
type Printfer interface {
Printf(msg string, args ...interface{})
}
Printfer is a Printf logger interface.
func ToPrintfer ¶
ToPrintfer converts ExtLogger to Printfer, which will use the INFO level.
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.
It is thread-safe for concurrent writes.
The default permission of the log file is 0644.
func NewSizedRotatingFileWithoutLock ¶
func NewSizedRotatingFileWithoutLock(filename string, size, count int, mode ...os.FileMode) (*SizedRotatingFile, error)
NewSizedRotatingFileWithoutLock is equal to NewSizedRotatingFile, But not use the lock to ensure that it's thread-safe to write the log.
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.
type StackField ¶
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 WriteCloser ¶
WriteCloser is the union of Writer and io.Closer.
func SyslogNetWriter ¶
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) (WriteCloser, error)
SyslogWriter opens a connection to the system syslog daemon by calling syslog.New and writes all logs to it.
func ToWriteCloser ¶
func ToWriteCloser(w Writer) WriteCloser
ToWriteCloser converts Writer to WriteCloser.
If the writer has no the method Close, it does nothing.
func WriteCloserFunc ¶
WriteCloserFunc adapts the write and close function to WriteCloser.
close may be nil, which will do nothing when calling the Close method.
type WriteFlushCloser ¶
type WriteFlushCloser interface { WriteCloser Flush() error }
WriteFlushCloser is the union of WriteCloser and Flusher.
func BufferWriter ¶
func BufferWriter(w Writer, bufferSize int) WriteFlushCloser
BufferWriter returns a new WriteFlushCloser to write all logs to a buffer which flushes into the wrapped writer whenever it is available for writing.
It uses SafeWriter to write all logs to the buffer thread-safely. So the first argument w may not be thread-safe.
func FailoverWriter ¶
func FailoverWriter(writers ...Writer) WriteFlushCloser
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) (WriteFlushCloser, 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 FileWriterWithoutLock ¶
func FileWriterWithoutLock(filename, filesize string, filenum int) (WriteFlushCloser, error)
FileWriterWithoutLock is the same as FileWriter, but not use the lock to ensure that it's thread-safe to write the log.
func LevelWriter ¶
func LevelWriter(lvl Level, w Writer) WriteFlushCloser
LevelWriter filters the logs whose level is less than lvl.
func NetWriter ¶
func NetWriter(network, addr string) (WriteFlushCloser, 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 SafeWriter ¶
func SafeWriter(w Writer) WriteFlushCloser
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, flush ...func() error) WriteFlushCloser
SplitWriter returns a level-separated writer, which will write the log record into the separated writer.
func StreamWriter ¶
func StreamWriter(w io.Writer) WriteFlushCloser
StreamWriter converts io.Writer to Writer.
func ToWriteFlushCloser ¶
func ToWriteFlushCloser(w Writer) WriteFlushCloser
ToWriteFlushCloser converts the Writer to WriteFlushCloser.
If the writer has no the methods Close and Flush, they do nothing.
func WriteFlushCloserFunc ¶
func WriteFlushCloserFunc(write func(Level, []byte) (int, error), flush, close func() error) WriteFlushCloser
WriteFlushCloserFunc adapts the write, flush and close function to WriteFlushCloser.
flush and close may be nil, which will do nothing when calling the Flush or Close method.