klog

package module
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2020 License: Apache-2.0 Imports: 21 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 v3.x and support Go 1.x.

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 (
	"os"

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

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

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

	log.Log(klog.LvlInfo, "log msg", klog.F("key1", "value1"), klog.F("key2", "value2"))
	log.Log(klog.LvlError, "log msg", klog.F("key1", "value1"), klog.F("key2", "value2"))

	// Output:
	// t=1574056059 logger=loggername 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 Log(level Level, msg string, fields ...Field)
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)

// 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 Ef(err error, format string, args ...interface{})

For example,

package main

import (
	"fmt"

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

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

	// 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=2019-11-18T14:01:08.7345586+08:00 lvl=ERROR caller=main.go:15 key1=value1 key2=value2 msg="msg"
	// t=2019-11-18T14:01:08.735969+08:00 lvl=ERROR caller=main.go:18 msg="errorf log msg"
	// t=2019-11-18T14:01:08.7360115+08:00 lvl=ERROR caller=main.go:19 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. It will use TextEncoder by default, but you can set it to others by SetEncoder or WithEncoder.

Writer
type Writer interface {
	Write(level Level, data []byte) (n int, err error)
}

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/v3"
)

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

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

	// Output to file test.log:
	// t=2019-11-18T14:18:01.479374+08:00 lvl=INFO key=value msg="hello world"
}

You can use WriterFunc or WriteCloserFunc to implement the interface Writer or WriteCloser.

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 194001346 6 0 0
BenchmarkKlogTextEncoder-4 42973323 24 0 0
BenchmarkKlogJSONEncoder-4 57550428 21 0 0
BenchmarkKlogTextEncoder10CtxFields-4 10026812 107 0 0
BenchmarkKlogJSONEncoder10CtxFields-4 6574923 221 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/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

Constants

This section is empty.

Variables

View Source
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.

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 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 Debug

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

Debug is equal to Log(LvlDebug, msg, field...).

func Debugf

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

Debugf is equal to Log(LvlDebug, Sprintf(format, args...)).

func Ef

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

Ef is equal to Kv("err", err).Log(LvlError, Sprintf(format, args...)).

func Error

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

Error is equal to Log(LvlError, msg, field...).

func Errorf

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

Errorf is equal to Log(LvlError, Sprintf(format, args...)).

func Fatal added in v3.1.0

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

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 Info

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

Info is equal to Log(LvlInfo, msg, field...).

func Infof

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

Infof is equal to Log(LvlInfo, Sprintf(format, args...)).

func Log

func Log(level Level, msg string, fields ...Field)

Log emits the log with the level by the default logger.

func NewStdLogger

func NewStdLogger(w Writer, prefix string, flags ...int) *log.Logger

NewStdLogger returns a new log.Logger with the writer.

If not giving flags, it is log.LstdFlags|log.Lmicroseconds|log.Lshortfile by default.

func Panic added in v3.1.0

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

Panic is equal to Log(LvlCrit, msg, fields...), then panic.

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

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(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 Sprintf

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

Sprintf is equal to fmt.Sprintf(msg, args...).

func ToIOWriter

func ToIOWriter(w Writer) io.WriteCloser

ToIOWriter converts Writer to io.WriteCloser.

func Trace

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

Trace is equal to Log(LvlTrace, msg, field...).

func Tracef

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

Tracef is equal to Log(LvlTrace, Sprintf(format, args...)).

func UpdateDefaultLogger

func UpdateDefaultLogger(level, filePath, fileSize string, fileNum int) error

UpdateDefaultLogger updates the default logger with NameToLevel(level) and FileWriter(filePath, fileSize, fileNum) if filePath is not "".

func Warn

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

Warn is equal to Log(LvlWarn, msg, field...).

func Warnf

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

Warnf is equal to Log(LvlWarn, Sprintf(format, 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 GetEncoder

func GetEncoder() Encoder

GetEncoder returns the encoder of the default logger.

func GetEncoderFromLogger

func GetEncoderFromLogger(logger Logger, defaultEncoder ...Encoder) Encoder

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

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 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

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 returns a new ExtLogger based on the default logger with the fields.

func WithDepth

func WithDepth(depth int) ExtLogger

WithDepth returns a new ExtLogger based on the default logger with the depth.

func WithEncoder

func WithEncoder(enc Encoder) ExtLogger

WithEncoder returns a new ExtLogger based on the default logger with the encoder.

func WithLevel

func WithLevel(level Level) ExtLogger

WithLevel returns a new ExtLogger based on the default logger with the level.

func WithName

func WithName(name string) ExtLogger

WithName returns a new ExtLogger based on the default logger with the 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 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

func ToFmtLogger(logger ExtLogger) FmtLogger

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

func NameToLevel(name string, defaultPanic ...bool) Level

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 NewLevel

func NewLevel(name string, priority int) Level

NewLevel returns a new level, which has also implemented the interface io.WriterTo.

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 Logger

type Logger interface {
	Log(level Level, msg string, fields ...Field)
}

Logger is an logger interface to emit the log.

type Printfer

type Printfer interface {
	Printf(msg string, args ...interface{})
}

Printfer is a Printf logger interface.

func ToPrintfer

func ToPrintfer(logger ExtLogger) Printfer

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.

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 WriteCloser

type WriteCloser interface {
	Writer
	io.Closer
}

WriteCloser is the union of Writer and io.Closer.

func SyslogNetWriter

func SyslogNetWriter(net, addr string, priority syslog.Priority, tag string) (WriteCloser, 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) (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

func WriteCloserFunc(write func(Level, []byte) (int, error), close func() error) WriteCloser

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 DiscardWriter

func DiscardWriter() WriteFlushCloser

DiscardWriter discards all the data.

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.

type Writer

type Writer interface {
	Write(level Level, data []byte) (n int, err error)
}

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

func WriterFunc

func WriterFunc(f func(Level, []byte) (int, 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