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 ¶
- Variables
- func Debug(msg string, fields ...Field)
- func Debugf(msg string, args ...interface{})
- func Ef(err error, format string, args ...interface{})
- func Error(msg string, fields ...Field)
- func Errorf(msg string, args ...interface{})
- func Fatal(msg string, fields ...Field)
- func Fatalf(msg string, args ...interface{})
- func FieldFunc(key string) func(value interface{}) Field
- func Info(msg string, fields ...Field)
- func Infof(msg string, args ...interface{})
- func ParseSize(s string) (size int64, err error)
- func Printf(msg string, args ...interface{})
- func RegisterCallOnExit(f func())
- func ToIOWriter(w Writer, lvl ...Level) io.WriteCloser
- func Trace(msg string, fields ...Field)
- func Tracef(msg string, args ...interface{})
- func Warn(msg string, fields ...Field)
- 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
- func EncoderFunc(w Writer, encode func(*Builder, Record)) Encoder
- func FixRecordEncoder(encoder Encoder, fixRecord func(Record) Record) 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 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
- func (l *ExtLogger) Clone() *ExtLogger
- func (l *ExtLogger) Debug(msg string, fields ...Field)
- func (l *ExtLogger) Debugf(msg string, args ...interface{})
- func (l *ExtLogger) Error(msg string, fields ...Field)
- func (l *ExtLogger) Errorf(msg string, args ...interface{})
- func (l *ExtLogger) Fatal(msg string, fields ...Field)
- func (l *ExtLogger) Fatalf(msg string, args ...interface{})
- func (l *ExtLogger) Info(msg string, fields ...Field)
- func (l *ExtLogger) Infof(msg string, args ...interface{})
- func (l *ExtLogger) Log(lvl Level, depth int, msg string, args []interface{}, fields []Field)
- func (l *ExtLogger) Printf(msg string, args ...interface{})
- func (l *ExtLogger) StdLog(prefix string, flags ...int) *log.Logger
- func (l *ExtLogger) Trace(msg string, fields ...Field)
- func (l *ExtLogger) Tracef(msg string, args ...interface{})
- func (l *ExtLogger) Warn(msg string, fields ...Field)
- func (l *ExtLogger) Warnf(msg string, args ...interface{})
- func (l *ExtLogger) WithCtx(ctxs ...Field) *ExtLogger
- func (l *ExtLogger) WithDepth(depth int) *ExtLogger
- func (l *ExtLogger) WithEncoder(e Encoder) *ExtLogger
- func (l *ExtLogger) WithLevel(level Level) *ExtLogger
- func (l *ExtLogger) WithName(name string) *ExtLogger
- type Field
- type FieldBuilder
- type FieldError
- type FieldReleaser
- type Level
- type Logger
- type Loggerf
- type Record
- type SizedRotatingFile
- type StackField
- type Writer
- func BufferWriter(w Writer, bufferSize int) Writer
- func DiscardWriter() Writer
- func FailoverWriter(writers ...Writer) Writer
- func FileWriter(filename, filesize string, filenum int) (Writer, error)
- func LevelWriter(lvl Level, w Writer) Writer
- func NetWriter(network, addr string) (Writer, error)
- func SafeWriter(w Writer) Writer
- func SplitWriter(getWriter func(Level) 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(write func(Level, []byte) (int, error), close ...func() error) Writer
Constants ¶
This section is empty.
Variables ¶
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 DefalutLogger = New("")
DefalutLogger is the default global logger.
Functions ¶
func Debugf ¶
func Debugf(msg string, args ...interface{})
Debugf is equal to DefalutLogger.Debugf(msg, args...).
func Errorf ¶
func Errorf(msg string, args ...interface{})
Errorf is equal to DefalutLogger.Errorf(msg, args...).
func Fatalf ¶
func Fatalf(msg string, args ...interface{})
Fatalf is equal to DefalutLogger.Fatalf(msg, args...).
func Infof ¶
func Infof(msg string, args ...interface{})
Infof is equal to DefalutLogger.Infof(msg, args...).
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(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 Tracef ¶
func Tracef(msg string, args ...interface{})
Tracef is equal to DefalutLogger.Tracef(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 ¶
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 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 ¶
ExtLogger is a extended logger implemented the Logger and Loggerf interface.
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 is equal to DefalutLogger.WithEncoder(enc).
func (*ExtLogger) Fatal ¶
Fatal implements the interface Logger, but call the exit functions in CallOnExit before the program exits.
func (*ExtLogger) Fatalf ¶
Fatalf implements the interface Loggerf, but call the exit functions in CallOnExit before the program exits.
func (*ExtLogger) WithEncoder ¶
WithEncoder returns a new ExtLogger with the new encoder.
type Field ¶
type Field interface { Key() string Value() interface{} }
Field represents a key-value pair.
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 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.
func NameToLevel ¶
NameToLevel returns a Level by the level name.
Support the level name, which is case insensitive:
TRACE DEBUG INFO WARN ERROR FATAL
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.
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 Writer ¶
Writer is the interface to write the log to the underlying storage.
func BufferWriter ¶
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 FailoverWriter ¶
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 ¶
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 ¶
LevelWriter filters the logs whose level is less than lvl.
func NetWriter ¶
NetWriter opens a socket to the given address and writes the log over the connection.
func SafeWriter ¶
SafeWriter is guaranteed that only a single writing operation can proceed at a time.
It's necessary for thread-safe concurrent writes.
func SplitWriter ¶
SplitWriter returns a level-separated writer, which will write the log record into the separated writer.
func StreamWriter ¶
StreamWriter converts io.Writer to Writer.
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.