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.
- 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 FromWriter(w Writer) io.WriteCloser
- func ParseSize(s string) (size int64, err error)
- type Builder
- func (b *Builder) AppendAny(any interface{}) (ok bool, err 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 Field
- type FmtLogger
- type FmtLoggerError
- type Hook
- type Level
- type Log
- type Logger
- func (l Logger) Debug(fields ...Field) Log
- func (l Logger) Error(fields ...Field) Log
- func (l Logger) Fatal(fields ...Field) Log
- 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) L(level Level, fields ...Field) Log
- func (l Logger) Level(level Level, fields ...Field) Log
- func (l Logger) Panic(fields ...Field) Log
- func (l Logger) Trace(fields ...Field) Log
- func (l Logger) Warn(fields ...Field) Log
- 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 FromWriter ¶
func FromWriter(w Writer) io.WriteCloser
FromWriter converts Writer to io.WriteCloser.
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 interface error interface fmt.Stringer interface encoding.TextMarshaler
For the unknown type, it does not append it and return false, or return true.
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 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 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...)`.
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) Level ¶
Level emits a log, the level of which is level.
You can gives some key-value field contexts optionally, which is equal to call Log.F(fields...).
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.