zaputils

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2019 License: MIT, MIT Imports: 13 Imported by: 0

README

wzap

A wrapper of zap supporting file rotating and more humanfriendly console output.

Quick Start

file writer.

package main

import "github.com/sevenNt/wzap"

var logger = wzap.New(
	wzap.WithPath("/tmp/async.log"), // set log path.
	wzap.WithLevel(wzap.Error),      // set log minimum level.
)

func main() {
	logger.Info("some information about LiLei",
		"name", "LiLei",
		"age", 17,
		"sex", "male",
	)
}

Fan-out

    package main

    import "github.com/sevenNt/wzap"

    var logger = wzap.New(
        // add a file writer.
        wzap.WithPath("/tmp/sync.log"),
        wzap.WithLevel(wzap.Error),
        wzap.WithOutput(
            wzap.WithOutput(
                // add another file writer.
                wzap.WithLevel(wzap.Info),
                wzap.WithPath("/tmp/info.log"),
            ),
            // add a console writer.
            wzap.WithOutput(
                wzap.WithLevelMask(wzap.DebugLevel|wzap.InfoLevel|wzap.WarnLevel),
                wzap.WithColorful(true),
                wzap.WithPrefix("H"),
                wzap.WithAsync(false),
            ),
            // add an another file writer.
            wzap.WithOutput(
                wzap.WithLevelMask(wzap.FatalLevel|wzap.ErrorLevel),
                wzap.WithPath("/tmp/error.log")
            ),
        )
    )

    func main() {
	    logger.Errorf("sync write %s", "How are you? I'm fine, thank you.")
	    logger.Debug("debug")
	    logger.Info("info")
	    logger.Warn("warn")
	    logger.Error("error")
	}

setting default fields.

  • setting global default fields.
	wzap.SetDefaultFields(
		wzap.String("aid", "12341234"),
		wzap.String("iid", "187281f-f983891-ff01923"),
		wzap.String("tid", "dasfasd-123asf-314dasfa"),
	)
  • setting default fields for single logger instance.
	logger := wzap.New(
		wzap.WithLevel(wzap.Info),
		wzap.WithPath("./defaultLogger.log"),
		wzap.WithFields(wzap.Int("appid", 100010), wzap.String("appname", "test-go")),
	)
	wzap.SetDefaultLogger(logger)
	wzap.Debug("debug")

Documentation

Index

Constants

View Source
const (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = 1 << iota
	// InfoLevel is the default logging priority.
	InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-Level logs.
	ErrorLevel
	// PanicLevel logs a message, then panics.
	PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel
)

A Level is a logging priority. Higher levels are more important.

View Source
const (
	ConsoleQueueLength = 1024 * 1024 * 10
)

Variables

This section is empty.

Functions

func Array

func Array(key string, val zapcore.ArrayMarshaler) zapcore.Field

Array constructs a field with the given key and ArrayMarshaler. It provides a flexible, but still type-safe and efficient, way to add array-like types to the logging context. The struct's MarshalLogArray method is called lazily.

func Bools

func Bools(key string, bs []bool) zapcore.Field

Bools constructs a field that carries a slice of bools.

func ByteStrings

func ByteStrings(key string, bss [][]byte) zapcore.Field

ByteStrings constructs a field that carries a slice of []byte, each of which must be UTF-8 encoded text.

func CheckErr

func CheckErr(err error, logFunc func(string, ...interface{})) (isErr bool)

CheckErr checks error with default logger.

func Complex128s

func Complex128s(key string, nums []complex128) zapcore.Field

Complex128s constructs a field that carries a slice of complex numbers.

func Complex64s

func Complex64s(key string, nums []complex64) zapcore.Field

Complex64s constructs a field that carries a slice of complex numbers.

func Debug

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

Debug logs debug level messages with default logger.

func Debugf

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

Debugf logs debug level messages with default logger in printf-style.

func DefaultDir

func DefaultDir() string

DefaultDir gets defaultDir.

func Durations

func Durations(key string, ds []time.Duration) zapcore.Field

Durations constructs a field that carries a slice of time.Durations.

func Error

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

Error logs Error level messages with default logger in structured-style. Notice: additional stack will be added into messages.

func Errorf

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

Errorf logs Error level messages with default logger in printf-style. Notice: additional stack will be added into messages.

func Errors

func Errors(key string, errs []error) zapcore.Field

Errors constructs a field that carries a slice of errors.

func Fatal

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

Fatal logs Fatal level messages with default logger in structured-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func Fatalf

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

Fatalf logs Fatalf level messages with default logger in printf-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func Float32s

func Float32s(key string, nums []float32) zapcore.Field

Float32s constructs a field that carries a slice of floats.

func Float64s

func Float64s(key string, nums []float64) zapcore.Field

Float64s constructs a field that carries a slice of floats.

func Info

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

Info logs Info level messages with default logger in structured-style.

func Infof

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

Infof logs Info level messages with default logger in printf-style.

func Int16s

func Int16s(key string, nums []int16) zapcore.Field

Int16s constructs a field that carries a slice of integers.

func Int32s

func Int32s(key string, nums []int32) zapcore.Field

Int32s constructs a field that carries a slice of integers.

func Int64s

func Int64s(key string, nums []int64) zapcore.Field

Int64s constructs a field that carries a slice of integers.

func Int8s

func Int8s(key string, nums []int8) zapcore.Field

Int8s constructs a field that carries a slice of integers.

func Ints

func Ints(key string, nums []int) zapcore.Field

Ints constructs a field that carries a slice of integers.

func Panic

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

Panic logs Panic level messages with default logger in structured-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func Panicf

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

Panicf logs Panicf level messages with default logger in printf-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func Register

func Register(name string, logger *Logger)

Register registers logger into loggers.

func SetDefaultDir

func SetDefaultDir(dir string)

SetDefaultDir sets default directory of all zap writer logger.

func SetDefaultFields

func SetDefaultFields(fs ...Field)

SetDefaultFields sets default fields of all logger.

func SetDefaultFileSuffix

func SetDefaultFileSuffix(suffix string)

SetDefaultFileSuffix sets default file suffix.

func SetDefaultLogger

func SetDefaultLogger(l *Logger)

SetDefaultLogger sets default logger with provided logger.

func Strings

func Strings(key string, ss []string) zapcore.Field

Strings constructs a field that carries a slice of strings.

func Sync

func Sync()

Sync syncs logger messages.

func Times

func Times(key string, ts []time.Time) zapcore.Field

Times constructs a field that carries a slice of time.Times.

func Uint16s

func Uint16s(key string, nums []uint16) zapcore.Field

Uint16s constructs a field that carries a slice of unsigned integers.

func Uint32s

func Uint32s(key string, nums []uint32) zapcore.Field

Uint32s constructs a field that carries a slice of unsigned integers.

func Uint64s

func Uint64s(key string, nums []uint64) zapcore.Field

Uint64s constructs a field that carries a slice of unsigned integers.

func Uint8s

func Uint8s(key string, nums []uint8) zapcore.Field

Uint8s constructs a field that carries a slice of unsigned integers.

func Uintptrs

func Uintptrs(key string, us []uintptr) zapcore.Field

Uintptrs constructs a field that carries a slice of pointer addresses.

func Uints

func Uints(key string, nums []uint) zapcore.Field

Uints constructs a field that carries a slice of unsigned integers.

func WDebug

func WDebug(log string, msg string, args ...interface{})

WDebug logs debug level messages with default logger.

func WDebugf

func WDebugf(log string, format string, args ...interface{})

WDebugf logs debug level messages with default logger.

func WError

func WError(log, msg string, args ...interface{})

WError logs Error level messages with default logger in structured-style. Notice: additional stack will be added into messages.

func WErrorf

func WErrorf(log, format string, args ...interface{})

WErrorf logs Error level messages with default logger in printf-style. Notice: additional stack will be added into messages.

func WFatal

func WFatal(log, msg string, args ...interface{})

WFatal logs Fatal level messages with default logger in structured-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func WFatalf

func WFatalf(log, format string, args ...interface{})

WFatalf logs Fatalf level messages with default logger in printf-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func WInfo

func WInfo(log string, msg string, args ...interface{})

WInfo logs Info level messages with default logger in structured-style.

func WInfof

func WInfof(log string, format string, args ...interface{})

WInfof logs Info level messages with default logger in structured-style.

func WPanic

func WPanic(log, msg string, args ...interface{})

WPanic logs Panic level messages with default logger in structured-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func WPanicf

func WPanicf(log, format string, args ...interface{})

WPanicf logs Panicf level messages with default logger in printf-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func WWarn

func WWarn(log string, msg string, args ...interface{})

WWarn logs Warn level messages with default logger in structured-style.

func WWarnf

func WWarnf(log string, format string, args ...interface{})

WWarnf logs Warn level messages with default logger in printf-style.

func Warn

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

Warn logs Warn level messages with default logger in structured-style.

func Warnf

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

Warnf logs Warn level messages with default logger in printf-style.

Types

type ConsoleWriter

type ConsoleWriter struct {
	// contains filtered or unexported fields
}

ConsoleWriter will print logger mesgaes into console

func NewConsoleWriter

func NewConsoleWriter(lv int, colorful bool, fs []Field) *ConsoleWriter

NewConsoleWriter constructs a new ConsoleWriter instance.

func (*ConsoleWriter) CheckErr

func (writer *ConsoleWriter) CheckErr(err error, logFunc func(string, ...interface{})) (isErr bool)

CheckErr checks error, error will be logged if it's not equal to nil.

func (*ConsoleWriter) Close

func (writer *ConsoleWriter) Close() error

Close closes writer.

func (*ConsoleWriter) Level

func (writer *ConsoleWriter) Level() int

Level return ConsoleWriter's level.

func (*ConsoleWriter) Print

func (writer *ConsoleWriter) Print(level int, msg string, keysAndValues ...interface{})

Print implements Writer Print method.

func (*ConsoleWriter) Printf

func (writer *ConsoleWriter) Printf(level int, format string, keysAndValues ...interface{})

Printf implements Writer Printf method.

func (*ConsoleWriter) SetAsync

func (writer *ConsoleWriter) SetAsync(async bool)

SetAsync sets async trigger.

func (*ConsoleWriter) SetPattern

func (writer *ConsoleWriter) SetPattern(pattern string)

SetPattern sets pattern.

func (*ConsoleWriter) SetPrefix

func (writer *ConsoleWriter) SetPrefix(prefix string)

SetPrefix sets prefix.

func (*ConsoleWriter) Start

func (writer *ConsoleWriter) Start()

Start start ConsoleWriter.

func (*ConsoleWriter) Sync

func (writer *ConsoleWriter) Sync() error

Sync flushes any buffered log entries.

func (*ConsoleWriter) Write

func (writer *ConsoleWriter) Write(str []byte) (n int, err error)

Write writes string into queue.

type Field

type Field = zapcore.Field

A Field is a marshaling operation used to add a key-value pair to a logger's context. Most fields are lazily marshaled, so it's inexpensive to add fields to disabled debug-level log statements.

func Any

func Any(key string, value interface{}) Field

Any takes a key and an arbitrary value and chooses the best way to represent them as a field, falling back to a reflection-based approach only if necessary.

Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between them. To minimize suprise, []byte values are treated as binary blobs, byte values are treated as uint8, and runes are always treated as integers.

func Binary

func Binary(key string, val []byte) Field

Binary constructs a field that carries an opaque binary blob.

Binary data is serialized in an encoding-appropriate format. For example, zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, use ByteString.

func Bool

func Bool(key string, val bool) Field

Bool constructs a field that carries a bool.

func ByteString

func ByteString(key string, val []byte) Field

ByteString constructs a field that carries UTF-8 encoded text as a []byte. To log opaque binary blobs (which aren't necessarily valid UTF-8), use Binary.

func Complex128

func Complex128(key string, val complex128) Field

Complex128 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex128 to interface{}).

func Complex64

func Complex64(key string, val complex64) Field

Complex64 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex64 to interface{}).

func DefaultFields

func DefaultFields() []Field

DefaultFields gets defaultFields.

func Duration

func Duration(key string, val time.Duration) Field

Duration constructs a field with the given key and value. The encoder controls how the duration is serialized.

func Err

func Err(err error) Field

Err is shorthand for the common idiom NamedError("error", err).

func Float32

func Float32(key string, val float32) Field

Float32 constructs a field that carries a float32. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Float64

func Float64(key string, val float64) Field

Float64 constructs a field that carries a float64. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Int

func Int(key string, val int) Field

Int constructs a field with the given key and value.

func Int16

func Int16(key string, val int16) Field

Int16 constructs a field with the given key and value.

func Int32

func Int32(key string, val int32) Field

Int32 constructs a field with the given key and value.

func Int64

func Int64(key string, val int64) Field

Int64 constructs a field with the given key and value.

func Int8

func Int8(key string, val int8) Field

Int8 constructs a field with the given key and value.

func NamedErr

func NamedErr(key string, err error) Field

NamedErr constructs a field that lazily stores err.Error() under the provided key. Errors which also implement fmt.Formatter (like those produced by github.com/pkg/errors) will also have their verbose representation stored under key+"Verbose". If passed a nil error, the field is a no-op.

For the common case in which the key is simply "error", the Error function is shorter and less repetitive.

func Namespace

func Namespace(key string) Field

Namespace creates a named, isolated scope within the logger's context. All subsequent fields will be added to the new namespace.

This helps prevent key collisions when injecting loggers into sub-components or third-party libraries.

func Object

func Object(key string, val zapcore.ObjectMarshaler) Field

Object constructs a field with the given key and ObjectMarshaler. It provides a flexible, but still type-safe and efficient, way to add map- or struct-like user-defined types to the logging context. The struct's MarshalLogObject method is called lazily.

func Reflect

func Reflect(key string, val interface{}) Field

Reflect constructs a field with the given key and an arbitrary object. It uses an encoding-appropriate, reflection-based function to lazily serialize nearly any object into the logging context, but it's relatively slow and allocation-heavy. Outside tests, Any is always a better choice.

If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect includes the error message in the final log output.

func Skip

func Skip() Field

Skip constructs a no-op field, which is often useful when handling invalid inputs in other Field constructors.

func String

func String(key string, val string) Field

String constructs a field with the given key and value.

func Stringer

func Stringer(key string, val fmt.Stringer) Field

Stringer constructs a field with the given key and the output of the value's String method. The Stringer's String method is called lazily.

func Time

func Time(key string, val time.Time) Field

Time constructs a zapcore.Field with the given key and value. The encoder controls how the time is serialized.

func Uint

func Uint(key string, val uint) Field

Uint constructs a field with the given key and value.

func Uint16

func Uint16(key string, val uint16) Field

Uint16 constructs a field with the given key and value.

func Uint32

func Uint32(key string, val uint32) Field

Uint32 constructs a field with the given key and value.

func Uint64

func Uint64(key string, val uint64) Field

Uint64 constructs a field with the given key and value.

func Uint8

func Uint8(key string, val uint8) Field

Uint8 constructs a field with the given key and value.

func Uintptr

func Uintptr(key string, val uintptr) Field

Uintptr constructs a field with the given key and value.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is an interface supports printf-style and structured-style logging.

func Default

func Default(name string) *Logger

Default returns a default Logger instance

func Log

func Log(name string) *Logger

Log returns logger with provided name.

func New

func New(opts ...Option) *Logger

New constructs a new Logger instance.

func (*Logger) CheckErr

func (l *Logger) CheckErr(err error, logFunc func(string, ...interface{})) (isErr bool)

CheckErr checks error, error will be logged if it's not equal to nil.

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...interface{})

Debug logs debug level messages.

func (Logger) Debugf

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

Debugf logs debug level messages in printf-style.

func (Logger) Error

func (l Logger) Error(msg string, args ...interface{})

Error logs Error level messages in structured-style. Notice: additional stack will be added into messages.

func (Logger) Errorf

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

Errorf logs Error level messages in printf-style. Notice: additional stack will be added into messages.

func (Logger) Fatal

func (l Logger) Fatal(msg string, args ...interface{})

Fatal logs Fatal level messages in structured-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func (Logger) Fatalf

func (l Logger) Fatalf(format string, args ...interface{})

Fatalf logs Fatalf level messages in printf-style. Notice: additional stack will be added into messages, then calls os.Exit(1).

func (*Logger) Info

func (l *Logger) Info(msg string, args ...interface{})

Info logs Info level messages in structured-style.

func (Logger) Infof

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

Infof logs Info level messages in printf-style.

func (Logger) Panic

func (l Logger) Panic(msg string, args ...interface{})

Panic logs Panic level messages in structured-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func (Logger) Panicf

func (l Logger) Panicf(format string, args ...interface{})

Panicf logs Panicf level messages in printf-style. Notice: additional stack will be added into messages, meanwhile logger will panic.

func (*Logger) Print

func (l *Logger) Print(level int, msg string, args ...interface{})

Print logs messages with provided level in structured-style.

func (*Logger) Printf

func (l *Logger) Printf(level int, format string, args ...interface{})

Printf logs messages with provided level in printf-style.

func (Logger) Sync

func (l Logger) Sync()

Sync syncs logger messages.

func (Logger) Warn

func (l Logger) Warn(msg string, args ...interface{})

Warn logs Warn level messages in structured-style.

func (Logger) Warnf

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

Warnf logs Warn level messages in printf-style.

type Option

type Option func(*Options)

Option is used to set options for the logger.

func WithAsync

func WithAsync(async bool) Option

WithAsync configures the console-logger's async trigger.

func WithColorful

func WithColorful(colorful bool) Option

WithColorful configures the console-logger's colorful trigger.

func WithFields

func WithFields(fs ...zapcore.Field) Option

WithFields adds fields to the logger.

func WithLevel

func WithLevel(lvFn func(string, ...interface{})) Option

WithLevel configures logger minimum level.

func WithLevelCombo

func WithLevelCombo(combo string) Option

WithLevelCombo configures logger's enabled levels with level-combo string. ex. "Warn | Error | Panic | Fatal" will enable Warn, Error, Panic and Fatal level logging.

func WithLevelMask

func WithLevelMask(lvMask int) Option

WithLevelMask configures logger's enabled levels with level masks.

func WithName

func WithName(name string) Option

WithName adds name to the logger.

func WithOutput

func WithOutput(opts ...Option) Option

WithOutput adds a new writer with options.

func WithOutputKV

func WithOutputKV(kv map[string]interface{}) Option

WithOutputKV adds a new writer with provided KV.

func WithOutputKVs

func WithOutputKVs(kvs []interface{}) Option

WithOutputKVs adds several new writers with provided KVs.

func WithPath

func WithPath(path string) Option

WithPath configures logger path.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix configures the console-logger's prefix.

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options wraps logger options.

type Writer

type Writer interface {
	Sync() error
	Level() int
	Print(int, string, ...interface{})
	Printf(int, string, ...interface{})
	CheckErr(error, func(string, ...interface{})) bool
}

Writer defines logger's writer.

type ZapWriter

type ZapWriter struct {
	// contains filtered or unexported fields
}

A ZapWriter wraps the zap.SugarWriter.

func NewZapWriter

func NewZapWriter(path string, level int, fs []Field) *ZapWriter

NewZapWriter constructs a new ZapWriter instance.

func (*ZapWriter) CheckErr

func (l *ZapWriter) CheckErr(err error, logFunc func(string, ...interface{})) (isErr bool)

CheckErr checks error, error will be logged if it's not equal to nil.

func (*ZapWriter) Level

func (l *ZapWriter) Level() int

Level return ZapWriter lever.

func (*ZapWriter) Print

func (l *ZapWriter) Print(level int, msg string, keysAndValues ...interface{})

Print logs message with structured-style.

func (*ZapWriter) Printf

func (l *ZapWriter) Printf(level int, format string, keysAndValues ...interface{})

Printf logs message with printf-style.

func (*ZapWriter) Sync

func (l *ZapWriter) Sync() error

Sync flushes any buffered log entries.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL