xlog

package module
v0.0.0-...-cfda439 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2020 License: MIT Imports: 18 Imported by: 13

README

xlog

Package xlog 是 zap 的简化版本。保留了 zap 大多数功能。 简单粗暴是 golang 的代码哲学,xlog 保持了这一传统。

特性

  1. 支持日志级别
  2. 支持日志名称和预置字段
  3. 支持控制台和JSON输出,并可以定制其他格式输出
  4. 支持简单的结构化字段
  5. 尽量不要使用昂贵的 fmt.Printf 和 reflect

Examples

Use Global Logger
const url = "http://example.com"

// 对于简单的应用可以直接通过使用全局日志函数来记录
// 使用fmt-style
xlog.Infof("Failed to fetch URL: %s", url)

// 使用结构化日志
xlog.Info("Failed to fetch URL.",
	xlog.F("url", url),
	xlog.F("attempt", 3),
	xlog.F("backoff", time.Second),
)
Use xlog.New
const url = "http://example.com"

l := xlog.New(xlog.NewCore(xlog.NewConsoleEncoder(Llongfile), xlog.Lock(os.Stderr), DebugLevel),
    xlog.AddCaller())
    
// 对于简单的应用可以直接通过使用全局日志函数来记录
// 使用fmt-style
l.Infof("Failed to fetch URL: %s", url)

// 使用结构化日志
l.Info("Failed to fetch URL.",
	xlog.F("url", url),
	xlog.F("attempt", 3),
	xlog.F("backoff", time.Second),
)

性能

由于简化了 zap 代码,整体性能优于 zap。

Documentation

Index

Constants

View Source
const (
	// Tdate the date in the local time zone: 2006-01-02
	Tdate = 1 << iota
	// Ttimeprefix add 'T' between date and time if set, otherwise add space.
	// Only with Ttime is valid
	Ttimeprefix
	// Ttime the time in the local time zone: 15:04:05
	Ttime
	// Tmilliseconds the time in the local time zone: 15:04:05.000
	Tmilliseconds
	// Tmicroseconds the time in the local time zone: 15:04:05.000000
	Tmicroseconds
	// Tnanoseconds the time in the local time zone: 15:04:05.000000000
	Tnanoseconds
	// TnineFlag use with Tmilliseconds or Tmicroseconds or Tnanoseconds.
	// If use this flag, 000... pattern switch to 999...
	TnineFlag
	// Tzone the local time zone: Z07:00
	Tzone
	// Tdatetime the date and time in the local time zone: 2006-01-02 15:04:05"
	Tdatetime = Tdate | Ttime
	// TdatetimeMilli the date and time(ms) in the local time zone: 2006-01-02 15:04:05.000"
	TdatetimeMilli = Tdate | Ttime | Tmilliseconds
	// TdatetimeMicro the date and time(ms) in the local time zone: 2006-01-02 15:04:05.000000"
	TdatetimeMicro = Tdate | Ttime | Tmicroseconds
	// TdatetimeNano the date and time(ms) in the local time zone: 2006-01-02 15:04:05.000000000"
	TdatetimeNano = Tdate | Ttime | Tnanoseconds
	// Trfc3339 is equivalent to time.RFC3339: 2006-01-02T15:04:05Z07:00
	Trfc3339 = Tdate | Ttimeprefix | Ttime | Tzone
	// Trfc3339Nano is equivalent to time.RFC3339Nano: 2006-01-02T15:04:05.999999999Z07:00
	Trfc3339Nano = Tdate | Ttimeprefix | Ttime | Tnanoseconds | TnineFlag | Tzone
)
View Source
const (
	Ldate         = 1 << iota     // the date in the local time zone: 2009-01-23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed. There is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only when Llongfile or Lshortfile is specified. For example, flags Ldate | Ltime (or LstdFlags) produce,

2009-01-23 01:23:23 message

while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,

2009-01-23 01:23:23.123123 /a/b/c/d.go:23: message

Variables

This section is empty.

Functions

func Debug

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

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Debugf

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

Debugf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at DebugLevel. The scene is as follows:

  1. args == nil, directly use template as message
  2. template = "", uses fmt.Sprint to construct message
  3. otherwise, uses fmt.Sprintf to construct message

func Error

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

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Errorf

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

Errorf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at ErrorLevel.

func Fatal

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

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func Fatalf

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

Fatalf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at FatalLevel. The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func Info

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

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Infof

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

Infof uses template or fmt.Sprint or fmt.Sprintf to log a templated message at InfoLevel.

func LevelEnabled

func LevelEnabled(lvl Level) bool

LevelEnabled 日志对象指定的级别是否启用

func Lock

func Lock(w io.Writer) io.Writer

Lock wraps a io.Writer in a mutex to make it safe for concurrent use. In particular, *os.Files must be locked before use.

func MultiWriter

func MultiWriter(writers ...io.Writer) io.Writer

MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

func Panic

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

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func Panicf

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

Panicf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at PanicLevel. The logger then panics, even if logging at PanicLevel is disabled.

func ReplaceGlobal

func ReplaceGlobal(logger *Logger) func()

ReplaceGlobal replaces the global Logger and SugaredLogger, and returns a function to restore the original values. It's safe for concurrent use.

func Warn

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

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Warnf

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

Warnf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at WarnLevel.

Types

type Builder

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

Builder provides a convenient way to build strings using Write or Append methods. It minimizes memory copying. The zero value is ready to use. It implements io.Writer and io.ByteWriter and io.StringWriter.

func (*Builder) AppendBool

func (b *Builder) AppendBool(v bool)

AppendBool appends "true" or "false", according to the value of v.

func (*Builder) AppendByteSlice

func (b *Builder) AppendByteSlice(v []byte)

AppendByteSlice appends a base64 string representing []byte v.

func (*Builder) AppendComplex128

func (b *Builder) AppendComplex128(val complex128)

AppendComplex128 appends the string form of the complex128 number f.

func (*Builder) AppendComplex64

func (b *Builder) AppendComplex64(val complex64)

AppendComplex64 appends the string form of the complex64 number f.

func (*Builder) AppendDuration

func (b *Builder) AppendDuration(d time.Duration)

AppendDuration appends the string form of the time.Duration.String().

func (*Builder) AppendFloat32

func (b *Builder) AppendFloat32(f float32)

AppendFloat32 appends the string form of the float32 number f.

func (*Builder) AppendFloat64

func (b *Builder) AppendFloat64(f float64)

AppendFloat64 appends the string form of the float64 number f.

func (*Builder) AppendHTMLQuote

func (b *Builder) AppendHTMLQuote(s string)

AppendHTMLQuote appends a double-quoted html string literal representing s.

func (*Builder) AppendInt

func (b *Builder) AppendInt(i int64)

AppendInt appends the string form of the int64 i.

func (*Builder) AppendJSON

func (b *Builder) AppendJSON(iv interface{}) (err error)

AppendJSON appends an json-style string literal representing v. It implements a json-encoded subset of encoding/json and remains compatible with encoding/json.

func (*Builder) AppendQuote

func (b *Builder) AppendQuote(s string)

AppendQuote appends a double-quoted Go string literal representing s.

func (*Builder) AppendTime

func (b *Builder) AppendTime(t time.Time, flag int)

AppendTime appends the textual representation in flag style to b. It has a faster formatting method that you can use if you are demanding performance, but it supports only a few formats

func (*Builder) AppendUint

func (b *Builder) AppendUint(i uint64)

AppendUint appends the string form of the uint64 i.

func (*Builder) AppendUintptr

func (b *Builder) AppendUintptr(p uintptr)

AppendUintptr appends the string form of the uintptr p.

func (*Builder) Bytes

func (b *Builder) Bytes() []byte

Bytes returns the builder's underlying byte slice.

func (*Builder) Cap

func (b *Builder) Cap() int

Cap returns the capacity of the builder's underlying byte slice. It is the total space allocated for the string being built and includes any bytes already written.

func (*Builder) Grow

func (b *Builder) Grow(n int)

Grow grows b's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to b without another allocation. If n is negative, Grow panics.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the number of accumulated bytes; b.Len() == len(b.String()).

func (*Builder) Reset

func (b *Builder) Reset()

Reset resets the Builder to be empty.

func (*Builder) String

func (b *Builder) String() string

String returns the accumulated string.

func (*Builder) Truncate

func (b *Builder) Truncate(n int)

Truncate discards all but the first n bytes from the b's buffer but continues to use the same allocated storage. It panics if n is negative or greater than b.Len().

func (*Builder) Write

func (b *Builder) Write(p []byte) (int, error)

Write implements io.Writer, appends the contents of p to b's buffer. Write always returns len(p), nil.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) error

WriteByte implements io.ByteWriter, appends the byte c to b's buffer. The returned error is always nil.

func (*Builder) WriteRune

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) (int, error)

WriteString implements io.StringWriter, appends the contents of s to b's buffer. It returns the length of s and a nil error.

type Core

type Core interface {
	LevelEnabler
	// Write serializes the Entry supplied at the log site and
	// writes them to their destination.
	//
	// If called, Write should always log the Entry; it should not
	// replicate the logic of Check.
	Write(e Entry) error
	// Sync flushes buffered logs (if any).
	Sync() error
}

Core is a minimal, fast logger interface. It's designed for library authors to wrap in a more user-friendly API.

func NewCore

func NewCore(enc Encoder, w io.Writer, enab LevelEnabler) Core

NewCore creates a Core that writes logs to a io.Writer.

func NewNopCore

func NewNopCore() Core

NewNopCore returns a no-op Core.

func NewTee

func NewTee(cores ...Core) Core

NewTee creates a Core that duplicates log entries into two or more underlying Cores.

Calling it with a single Core returns the input unchanged, and calling it with no input returns a no-op Core.

type Encoder

type Encoder interface {
	// Encode encodes a log entry to b
	Encode(b *Builder, e Entry) error
}

Encoder is a format-agnostic interface for all log entry marshalers.

func NewConsoleEncoder

func NewConsoleEncoder(flags int) Encoder

NewConsoleEncoder returns an encoder whose output is designed for human - rather than machine - consumption.

func NewJSONEncoder

func NewJSONEncoder(flags int) Encoder

NewJSONEncoder returns a fast, low-allocation JSON encoder. The encoder appropriately escapes all field keys and values.

type Entry

type Entry struct {
	Level      Level
	Time       time.Time
	Caller     EntryCaller
	Message    string
	Fields     []Field
	LoggerName string
	Ctx        []Field
}

Entry represents a log entry.

type EntryCaller

type EntryCaller struct {
	Defined bool
	PC      uintptr
	File    string
	Line    int
}

EntryCaller represents the caller of a logging function.

func NewEntryCaller

func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller

NewEntryCaller makes an EntryCaller from the return signature of runtime.Caller.

type Field

type Field struct {
	Key string
	Val interface{}
}

Field represents a custom fielda of log entry.

func F

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

F .

func (Field) MarshalJSON

func (f Field) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (Field) String

func (f Field) String() string

String .

type Level

type Level int8

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

const (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel Level = iota - 1
	// 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
)

func LevelFlag

func LevelFlag(name string, defaultLevel Level, usage string) *Level

LevelFlag defines a Level flag with specified name, default value, and usage string. The return value is the address of a Level variable that stores the value of the flag.

func (Level) CapitalString

func (l Level) CapitalString() string

CapitalString returns an all-caps ASCII representation of the log level.

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

Enabled returns true if the given level is at or above this level.

func (*Level) Get

func (l *Level) Get() interface{}

Get gets the level for the flag.Getter interface.

func (Level) MarshalText

func (l Level) MarshalText() ([]byte, error)

MarshalText marshals the Level to text. Note that the text representation drops the -Level suffix (see example).

func (*Level) Set

func (l *Level) Set(s string) error

Set sets the level for the flag.Value interface.

func (Level) String

func (l Level) String() string

String returns a lower-case ASCII representation of the log level.

func (*Level) UnmarshalText

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText expects the text representation of a Level to drop the -Level suffix (see example).

In particular, this makes it easy to configure logging levels using YAML, TOML, or JSON files.

type LevelEnabler

type LevelEnabler interface {
	Enabled(Level) bool
}

LevelEnabler decides whether a given logging level is enabled when logging a message.

Enablers are intended to be used to implement deterministic filters; concerns like sampling are better implemented as a Core.

Each concrete Level value implements a static LevelEnabler which returns true for itself and all higher logging levels. For example WarnLevel.Enabled() will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and FatalLevel, but return false for InfoLevel and DebugLevel.

type Logger

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

A Logger provides fast, leveled, structured logging. All methods are safe for concurrent use.

func L

func L() *Logger

L returns the global Logger, which can be reconfigured with ReplaceGlobals. It's safe for concurrent use.

func New

func New(core Core, options ...Option) *Logger

New constructs a new Logger from the provided Core and Options. If the passed Core is nil, it falls back to using a no-op implementation.

func (*Logger) Core

func (l *Logger) Core() Core

Core returns the Logger's underlying Core.

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Debugf

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

Debugf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at DebugLevel. The scene is as follows:

  1. args == nil, directly use template as message
  2. template = "", uses fmt.Sprint to construct message
  3. otherwise, uses fmt.Sprintf to construct message

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Errorf

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

Errorf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at ErrorLevel.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*Logger) Fatalf

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

Fatalf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at FatalLevel. The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Infof

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

Infof uses template or fmt.Sprint or fmt.Sprintf to log a templated message at InfoLevel.

func (*Logger) LevelEnabled

func (l *Logger) LevelEnabled(lvl Level) bool

LevelEnabled 日志对象指定的级别是否启用

func (*Logger) Panic

func (l *Logger) Panic(msg string, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (*Logger) Panicf

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

Panicf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at PanicLevel. The logger then panics, even if logging at PanicLevel is disabled.

func (*Logger) Sync

func (l *Logger) Sync() error

Sync calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Warnf

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

Warnf uses template or fmt.Sprint or fmt.Sprintf to log a templated message at WarnLevel.

func (*Logger) With

func (l *Logger) With(opts ...Option) *Logger

With clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

type O

type O []Field

O represents an object consisting of fields.

func (O) MarshalJSON

func (o O) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

type Option

type Option interface {
	// contains filtered or unexported methods
}

An Option configures a Logger.

func AddCaller

func AddCaller() Option

AddCaller configures the Logger to annotate each message with the filename and line number of caller.

func AddCallerSkip

func AddCallerSkip(skip int) Option

AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option).

When building wrappers around the Logger, use this option to set the wrapping depth.

func Fields

func Fields(fs ...Field) Option

Fields adds preset fields to the Logger.

func Named

func Named(s string) Option

Named adds a new path segment to the logger's name. Segments are joined by periods with '.'.

Jump to

Keyboard shortcuts

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