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 ¶
- Variables
- func AppendCleaner(clean ...func())
- func Debugf(msg string, args ...interface{})
- func Errorf(msg string, args ...interface{})
- func Fatalf(msg string, args ...interface{})
- func FromWriter(w Writer) io.WriteCloser
- func Infof(msg string, args ...interface{})
- func Lf(level Level, msg string, args ...interface{})
- func Panicf(msg string, args ...interface{})
- func ParseSize(s string) (size int64, err error)
- func Tracef(msg string, args ...interface{})
- func Warnf(msg 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
- type Errors
- type Field
- type FmtLogger
- type FmtLoggerError
- type FmtLoggerf
- type Hook
- type KV
- type LLog
- func (l LLog) Debugf(msg string, args ...interface{})
- func (l LLog) E(err error) LLog
- func (l LLog) Errorf(msg string, args ...interface{})
- func (l LLog) F(fields ...Field) LLog
- func (l LLog) Fatalf(msg string, args ...interface{})
- func (l LLog) Infof(msg string, args ...interface{})
- func (l LLog) K(key string, value interface{}) LLog
- func (l LLog) Levelf(lvl Level, msg string, args ...interface{})
- func (l LLog) Lf(lvl Level, msg string, args ...interface{})
- func (l LLog) Panicf(msg string, args ...interface{})
- func (l LLog) Tracef(msg string, args ...interface{})
- func (l LLog) V(kvs ...KV) LLog
- func (l LLog) Warnf(msg string, args ...interface{})
- type Level
- type Log
- func (l Log) E(err error) Log
- func (l Log) F(fields ...Field) Log
- func (l Log) K(key string, value interface{}) Log
- func (l Log) Msg(args ...interface{})
- func (l Log) Msgf(format string, args ...interface{})
- func (l Log) Print(args ...interface{})
- func (l Log) Printf(format string, args ...interface{})
- func (l Log) V(kvs ...KV) Log
- type Logger
- func (l Logger) AddDepth(depth int) Logger
- func (l Logger) Debug(fields ...Field) Log
- func (l Logger) Debugf(msg string, args ...interface{})
- func (l Logger) E(err error) LLog
- func (l Logger) Error(fields ...Field) Log
- func (l Logger) Errorf(msg string, args ...interface{})
- func (l Logger) F(fields ...Field) LLog
- func (l Logger) Fatal(fields ...Field) Log
- func (l Logger) Fatalf(msg string, args ...interface{})
- func (l Logger) GetDepth() int
- func (l Logger) GetLevel() Level
- func (l Logger) GetName() string
- func (l Logger) GetWriter() Writer
- func (l Logger) Info(fields ...Field) Log
- func (l Logger) Infof(msg string, args ...interface{})
- func (l Logger) K(key string, value interface{}) LLog
- func (l Logger) L(level Level, fields ...Field) Log
- func (l Logger) Level(level Level, fields ...Field) Log
- func (l Logger) Levelf(level Level, msg string, args ...interface{})
- func (l Logger) Lf(level Level, msg string, args ...interface{})
- func (l Logger) Panic(fields ...Field) Log
- func (l Logger) Panicf(msg string, args ...interface{})
- func (l Logger) Trace(fields ...Field) Log
- func (l Logger) Tracef(msg string, args ...interface{})
- func (l Logger) V(kvs ...KV) LLog
- func (l Logger) Warn(fields ...Field) Log
- func (l Logger) Warnf(msg string, args ...interface{})
- func (l Logger) WithDepth(depth int) Logger
- func (l Logger) WithEncoder(encoder Encoder) Logger
- func (l Logger) WithField(fields ...Field) Logger
- func (l Logger) WithHook(hook ...Hook) Logger
- func (l Logger) WithKv(key string, value interface{}) Logger
- func (l Logger) WithLevel(level Level) Logger
- func (l Logger) WithName(name string) Logger
- func (l Logger) WithWriter(w Writer) Logger
- type Record
- type SizedRotatingFile
- type Valuer
- type Writer
- func DiscardWriter() Writer
- func FailoverWriter(outs ...Writer) Writer
- func LevelWriter(lvl Level, w Writer) Writer
- func MultiWriter(outs ...Writer) Writer
- func NetWriter(network, addr string) (Writer, error)
- func ReopenWriter(factory func() (w io.WriteCloser, reopen <-chan bool, err error)) Writer
- func SafeWriter(w Writer) Writer
- func StreamWriter(w io.Writer) Writer
- func SyslogNetWriter(net, addr string, priority syslog.Priority, tag string) (Writer, error)
- func SyslogWriter(priority syslog.Priority, tag string) (Writer, error)
- func WriterFunc(w func(Level, []byte) (int, error), close ...func() error) Writer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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.
var Std = New()
Std is the global default 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 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 Lf ¶ added in v1.2.0
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 ¶
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
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 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
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 ¶
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".
func StdJSONEncoder ¶
func StdJSONEncoder() Encoder
StdJSONEncoder is equal to JSONEncoder, which uses json.Marshal() to encode it, but the performance is a little bad.
func TextEncoder ¶
func TextEncoder() 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".
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 ¶
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 ¶
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 ¶
DisableLogger disables the logger, whose name is in names, to emit the log.
func DisableLoggerFromEnv ¶
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 ¶
EnableLogger allows the logger, whose name is in names, to emit the log.
func EnableLoggerFromEnv ¶
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 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.
func (LLog) F ¶ added in v1.2.0
F appends more than one key-value pair into the structured log by the field.
type Level ¶
type Level int32
Level represents a level. The bigger the value, the higher the level.
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 ¶
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 ¶
MarshalJSON implements json.Marshaler.
type Log ¶
type Log struct {
// contains filtered or unexported fields
}
Log is used to emit a structured key-value 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 ¶
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...)`.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is a structured logger based on key-value.
func New ¶
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 ¶
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.
func (Logger) AddDepth ¶ added in v1.2.0
AddDepth is the same as WithDepth(depth), but it will grow it with depth, not reset it to depth.
func (Logger) Debug ¶
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
Debugf emits a DEBUG log, which is equal to l.Levelf(LvlDebug, msg, args...).
func (Logger) E ¶ added in v1.3.0
E is equal to l.K("err", err).
Notice: you must continue to call the level method, such as Levelf(), Debugf(), Infof(), Errorf(), etc, to trigger it.
func (Logger) Error ¶
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
Errorf emits a ERROR log, which is equal to l.Levelf(LvlError, msg, args...).
func (Logger) F ¶ added in v1.2.0
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 ¶
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
Fatalf emits a FATAL log, which is equal to l.Levelf(LvlFatal, msg, args...).
func (Logger) Info ¶
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
Infof emits a INFO log, which is equal to l.Levelf(LvlInfo, msg, args...).
func (Logger) K ¶ added in v1.2.0
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 ¶
L is short for Level(level, fields...).
Notice: you must continue to call Msg() or Msgf() to trigger it.
func (Logger) Level ¶
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
Levelf emits a specified `level` log, which is equal to l.F().Levelf(level, msg, args...).
func (Logger) Panic ¶
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
Panicf emits a PANIC log, which is equal to l.Levelf(LvlPanic, msg, args...).
func (Logger) Trace ¶
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
Tracef emits a TRACE log, which is equal to l.Levelf(LvlTrace, msg, args...).
func (Logger) Warn ¶
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
Warnf emits a WARN log, which is equal to l.Levelf(LvlWarn, msg, args...).
func (Logger) WithDepth ¶
WithDepth returns a new Logger with the caller depth.
Notice: 0 stands for the stack where the caller is.
func (Logger) WithEncoder ¶
WithEncoder returns a new Logger with the encoder.
func (Logger) WithKv ¶
WithKv returns a new Logger with the new key-value context, which is equal to
l.WithField(Field{Key: key, Value: value})
func (Logger) WithWriter ¶
WithWriter returns a new Logger with the writer w.
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.
type Valuer ¶
type Valuer func(Record) (v interface{})
Valuer is used to represent a lazy value by calling a function.
func Caller ¶
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 ¶
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 LineNoAsInt ¶
func LineNoAsInt() Valuer
LineNoAsInt returns the line number of the caller.
Return 0 if the line is missing.
type Writer ¶
Writer is the interface to write the log to the underlying storage.
func FailoverWriter ¶
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 LevelWriter ¶
LevelWriter filters the logs whose level is less than lvl.
func MultiWriter ¶
MultiWriter writes one data to more than one destination.
func NetWriter ¶
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 ¶
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 ¶
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 ¶
SyslogNetWriter opens a connection to a log daemon over the network and writes all logs to it.
func SyslogWriter ¶
SyslogWriter opens a connection to the system syslog daemon by calling syslog.New and writes all logs to it.