logf

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2020 License: MIT Imports: 18 Imported by: 0

README

logf

GoDoc Build Status Go Report Status Coverage Status

Faster-than-light, asynchronous, structured logger in Go with zero allocation count.

Example

The following example creates a new logf logger and logs a message.

package main

import (
    "runtime"

    "github.com/ssgreg/logf"
)

func main() {
    // The default channel writer writes to stdout using json encoder.
    writer, writerClose := logf.NewChannelWriter.Default()
    defer writerClose()

    logger := logf.NewLogger(logf.LevelInfo, writer)

    logger.Info("got cpu info", logf.Int("count", runtime.NumCPU()))
}

The output is the following:

{"level":"info","ts":"2018-11-03T09:49:56+03:00","msg":"got cpu info","count":8}

Benchmarks

TODO

TODOs

Benchmarks:

  • benchmarks descriptions
  • non-parallel execution explanation
  • scenario decomposition
  • use zerolog object and array marshaller
  • add checked logging for normal (not disabled) cases

Encoder:

  • move to clone
  • use EscapeString instead

Documentation

Index

Constants

View Source
const (
	DefaultFieldKeyLevel  = "level"
	DefaultFieldKeyMsg    = "msg"
	DefaultFieldKeyTime   = "ts"
	DefaultFieldKeyName   = "logger"
	DefaultFieldKeyCaller = "caller"
)

Default field keys.

View Source
const (
	PageSize = 4 * 1024
)

PageSize is the recommended buffer size.

Variables

View Source
var NewChannelWriter = channelWriterGetter(
	func(cfg ChannelWriterConfig) (EntryWriter, ChannelWriterCloseFunc) {
		l := &channelWriter{}
		l.init(cfg.WithDefaults())

		return l, ChannelWriterCloseFunc(
			func() {
				l.close()
			})
	},
)

NewChannelWriter returns a new ChannelWriter with the given config.

View Source
var NewErrorEncoder = errorEncoderGetter(
	func(c ErrorEncoderConfig) ErrorEncoder {
		return func(key string, err error, enc FieldEncoder) {
			encodeError(key, err, enc, c.WithDefaults())
		}
	},
)

NewErrorEncoder creates the new instance of the ErrorEncoder with the given ErrorEncoderConfig.

View Source
var NewJSONEncoder = jsonEncoderGetter(
	func(cfg JSONEncoderConfig) Encoder {
		return &jsonEncoder{cfg.WithDefaults(), NewCache(100), nil, 0}
	},
)

NewJSONEncoder creates the new instance of the JSON Encoder with the given JSONEncoderConfig.

View Source
var NewJSONTypeEncoderFactory = jsonTypeEncoderFactoryGetter(
	func(c JSONEncoderConfig) TypeEncoderFactory {
		return &jsonEncoder{c.WithDefaults(), nil, nil, 0}
	},
)

NewJSONTypeEncoderFactory creates the new instance of the JSON TypeEncoderFactory with the given JSONEncoderConfig.

Functions

func AppendBool

func AppendBool(b *Buffer, n bool)

AppendBool appends "true" or "false", according to the given bool to the given Buffer.

func AppendFloat32

func AppendFloat32(b *Buffer, n float32)

AppendFloat32 appends the string form of the given float32 to the given Buffer.

func AppendFloat64

func AppendFloat64(b *Buffer, n float64)

AppendFloat64 appends the string form of the given float32 to the given Buffer.

func AppendInt

func AppendInt(b *Buffer, n int64)

AppendInt appends the string form in the base 10 of the given integer to the given Buffer.

func AppendUint

func AppendUint(b *Buffer, n uint64)

AppendUint appends the string form in the base 10 of the given unsigned integer to the given Buffer.

func DefaultErrorEncoder

func DefaultErrorEncoder(key string, err error, enc FieldEncoder)

DefaultErrorEncoder encodes the given error as a set of fields.

A mandatory field with the given key and an optional field with the full verbose error message.

func DefaultLevelEncoder

func DefaultLevelEncoder(lvl Level, m TypeEncoder)

DefaultLevelEncoder implements LevelEncoder by calling Level itself.

func EscapeByteString

func EscapeByteString(buf *Buffer, s []byte) error

EscapeByteString processes a single escape sequence to the given Buffer.

func EscapeString

func EscapeString(buf *Buffer, s string) error

EscapeString processes a single escape sequence to the given Buffer.

func FloatSecondsDurationEncoder

func FloatSecondsDurationEncoder(d time.Duration, e TypeEncoder)

FloatSecondsDurationEncoder encodes the given Duration to a floating-point number of seconds elapsed.

func FullCallerEncoder

func FullCallerEncoder(c EntryCaller, m TypeEncoder)

FullCallerEncoder encodes the given EntryCaller using a full file path.

func NanoDurationEncoder

func NanoDurationEncoder(d time.Duration, e TypeEncoder)

NanoDurationEncoder encodes the given Duration as a number of nanoseconds.

func NewContext

func NewContext(parent context.Context, logger *Logger) context.Context

NewContext returns a new Context with the given Logger inside it.

func RFC3339NanoTimeEncoder

func RFC3339NanoTimeEncoder(t time.Time, e TypeEncoder)

RFC3339NanoTimeEncoder encodes the given Time as a string using RFC3339Nano layout.

func RFC3339TimeEncoder

func RFC3339TimeEncoder(t time.Time, e TypeEncoder)

RFC3339TimeEncoder encodes the given Time as a string using RFC3339 layout.

func ShortCallerEncoder

func ShortCallerEncoder(c EntryCaller, m TypeEncoder)

ShortCallerEncoder encodes the given EntryCaller using it's FileWithPackage function.

func StringDurationEncoder

func StringDurationEncoder(d time.Duration, m TypeEncoder)

StringDurationEncoder encodes the given Duration as a string using Stringer interface.

func UnixNanoTimeEncoder

func UnixNanoTimeEncoder(t time.Time, e TypeEncoder)

UnixNanoTimeEncoder encodes the given Time as a Unix time, the number of of nanoseconds elapsed since January 1, 1970 UTC.

func UpperCaseLevelEncoder

func UpperCaseLevelEncoder(lvl Level, m TypeEncoder)

UpperCaseLevelEncoder implements LevelEncoder by calling Level itself.

Types

type Appender

type Appender interface {
	// Append logs the Entry in Appender specific way.
	Append(Entry) error

	// Flush writes uncommitted changes to the underlying buffer of Writer.
	Flush() error

	// Sync writes uncommitted changes to the stable storage. For files this
	// means flushing the file system's in-memory copy of recently written
	// data to disk.
	Sync() error
}

Appender is the interface for your own strategies for outputting log entries.

func NewDiscardAppender

func NewDiscardAppender() Appender

NewDiscardAppender returns a new Appender that does nothing.

func NewWriteAppender

func NewWriteAppender(w io.Writer, enc Encoder) Appender

NewWriteAppender returns a new Appender with the given Writer and Encoder.

type ArrayEncoder

type ArrayEncoder interface {
	EncodeLogfArray(TypeEncoder) error
}

ArrayEncoder defines the interface to create your own array logger.

Example:

type stringArray []string

func (o stringArray) EncodeLogfArray(e TypeEncoder) error {
	for i := range o {
		e.EncodeTypeString(o[i])
	}

	return nil
}

type Buffer

type Buffer struct {
	Data []byte
}

Buffer is a helping wrapper for byte slice.

func NewBuffer

func NewBuffer() *Buffer

NewBuffer creates the new instance of Buffer with default capacity.

func NewBufferWithCapacity

func NewBufferWithCapacity(capacity int) *Buffer

NewBufferWithCapacity creates the new instance of Buffer with the given capacity.

func (*Buffer) AppendByte

func (b *Buffer) AppendByte(data byte)

AppendByte appends a single byte to the Buffer.

func (*Buffer) AppendBytes

func (b *Buffer) AppendBytes(data []byte)

AppendBytes appends a byte slice to the Buffer.

func (*Buffer) AppendString

func (b *Buffer) AppendString(data string)

AppendString appends a string to the Buffer.

func (*Buffer) Back

func (b *Buffer) Back() byte

Back returns the last byte of the underlying byte slice. A caller is in charge of checking that the Buffer is not empty.

func (*Buffer) Bytes

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

Bytes returns the underlying byte slice as is.

func (*Buffer) Cap

func (b *Buffer) Cap() int

Cap returns the capacity of the underlying byte slice.

func (*Buffer) EnsureSize

func (b *Buffer) EnsureSize(s int) []byte

EnsureSize ensures that the Buffer is able to append 's' bytes without a further realloc.

func (*Buffer) ExtendBytes

func (b *Buffer) ExtendBytes(s int) []byte

ExtendBytes extends the Buffer with the given size and returns a slice tp extended part of the Buffer.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the length of the underlying byte slice.

func (*Buffer) Reset

func (b *Buffer) Reset()

Reset resets the underlying byte slice.

func (*Buffer) String

func (b *Buffer) String() string

String implements fmt.Stringer.

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (n int, err error)

Write implements io.Writer.

type Cache

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

Cache is the simple implementation of LRU cache. The Cache is not goroutine safe.

func NewCache

func NewCache(limit int) *Cache

NewCache returns a new Cache with the given limit.

func (*Cache) Clean

func (c *Cache) Clean()

Clean removes all buffers from the cache.

func (*Cache) Get

func (c *Cache) Get(k int32) ([]byte, bool)

Get returns cached buffer for the given key.

func (*Cache) Len

func (c *Cache) Len() int

Len returns the count of cached buffers.

func (*Cache) Set

func (c *Cache) Set(k int32, bytes []byte)

Set adds the given buffer with the given key to the cache or replaces the existing one with the same key.

type CallerEncoder

type CallerEncoder func(EntryCaller, TypeEncoder)

CallerEncoder is the function type to encode the given EntryCaller.

type ChannelWriterCloseFunc

type ChannelWriterCloseFunc func()

ChannelWriterCloseFunc allows to close channel writer.

type ChannelWriterConfig

type ChannelWriterConfig struct {
	// Capacity specifies the underlying channel capacity.
	Capacity int

	// Appender specified the basic Appender for all Entries.
	//
	// Default Appender is WriterAppender with JSON Encoder.
	Appender Appender

	// ErrorAppender specifies the Appender for errors returning by basic
	// Appender.
	//
	// Default ErrorAppender does nothing.
	ErrorAppender Appender

	// EnableSyncOnError specifies whether Appender.Sync should be called
	// for messages with LevelError or not.
	//
	// Default value is false.
	EnableSyncOnError bool
}

ChannelWriterConfig allows to configure ChannelWriter.

func (ChannelWriterConfig) WithDefaults

func (c ChannelWriterConfig) WithDefaults() ChannelWriterConfig

WithDefaults returns the new config in which all uninitialized fields are filled with their default values.

type DurationEncoder

type DurationEncoder func(time.Duration, TypeEncoder)

DurationEncoder is the function type to encode the given Duration.

type Encoder

type Encoder interface {
	Encode(*Buffer, Entry) error
}

Encoder defines the interface to create your own log format.

In case of error, Encoder must remove bytes related to the given Entry from the Buffer.

type Entry

type Entry struct {
	// LoggerID specifies a unique logger identifies.
	LoggerID int32

	// LoggerName specifies a non-unique name of a logger.
	// Can be empty.
	LoggerName string

	// DeriviedFields specifies logger data fields including fields of
	// logger parents. The earliest fields (parent's fields) go first.
	DerivedFields []Field

	// Fields specifies data fields of a log message.
	Fields []Field

	// Level specifies a severity level of a log message.
	Level Level

	// Time specifies a timestamp of a log message.
	Time time.Time

	// Text specifies a text message of a log message.
	Text string

	// Caller specifies file:line info about an Entry's caller.
	Caller EntryCaller
}

Entry holds a single log message and fields.

type EntryCaller

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

EntryCaller holds values returned by runtime.Caller.

func NewEntryCaller

func NewEntryCaller(skip int) EntryCaller

NewEntryCaller creates an instance of EntryCaller with the given number of frames to skip.

func (EntryCaller) FileWithPackage

func (c EntryCaller) FileWithPackage() string

FileWithPackage cuts a package name and a file name from EntryCaller.File.

type EntryWriter

type EntryWriter interface {
	WriteEntry(Entry)
}

EntryWriter is the interface that should do real logging stuff.

func NewUnbufferedEntryWriter

func NewUnbufferedEntryWriter(appender Appender) EntryWriter

NewUnbufferedEntryWriter returns an implementation of EntryWriter which puts entries directly to the appender immediately and synchronously.

type ErrorEncoder

type ErrorEncoder func(string, error, FieldEncoder)

ErrorEncoder is the function type to encode the given error.

type ErrorEncoderConfig

type ErrorEncoderConfig struct {
	VerboseFieldSuffix string
	NoVerboseField     bool
}

ErrorEncoderConfig allows to configure ErrorEncoder.

func (ErrorEncoderConfig) WithDefaults

func (c ErrorEncoderConfig) WithDefaults() ErrorEncoderConfig

WithDefaults returns the new config in which all uninitialized fields are filled with their default values.

type Field

type Field struct {
	Key   string
	Type  FieldType
	Any   interface{}
	Int   int64
	Bytes []byte
}

Field hold data of a specific field.

func Any

func Any(k string, v interface{}) Field

Any returns a new Filed with the given key and value of any type. Is tries to choose the best way to represent key-value pair as a Field.

Note that Any is not possible to choose ConstX methods. Use specific Field methods for better performance.

func Array

func Array(k string, v ArrayEncoder) Field

Array returns a new Field with the given key and ArrayEncoder.

func Bool

func Bool(k string, v bool) Field

Bool returns a new Field with the given key and bool.

func Bools

func Bools(k string, v []bool) Field

Bools returns a new Field with the given key and slice of bools.

func Bytes

func Bytes(k string, v []byte) Field

Bytes returns a new Field with the given key and slice of bytes.

func ConstBools

func ConstBools(k string, v []bool) Field

ConstBools returns a new Field with the given key and slice of bools.

Call ConstBools if your array is const. It has significantly less impact on the calling goroutine.

func ConstBytes

func ConstBytes(k string, v []byte) Field

ConstBytes returns a new Field with the given key and slice of bytes.

Call ConstBytes if your array is const. It has significantly less impact on the calling goroutine.

func ConstDurations

func ConstDurations(k string, v []time.Duration) Field

ConstDurations returns a new Field with the given key and slice of time.Duration.

Call ConstDurations if your array is const. It has significantly less impact on the calling goroutine.

func ConstFloats32

func ConstFloats32(k string, v []float32) Field

ConstFloats32 returns a new Field with the given key and slice of 32-bit floats.

Call ConstFloats32 if your array is const. It has significantly less impact on the calling goroutine.

func ConstFloats64

func ConstFloats64(k string, v []float64) Field

ConstFloats64 returns a new Field with the given key and slice of 64-bit floats.

Call ConstFloats64 if your array is const. It has significantly less impact on the calling goroutine.

func ConstFormatter

func ConstFormatter(k string, verb string, v interface{}) Field

ConstFormatter returns a new Field with the given key, verb and interface to format.

Call ConstFormatter if your object is const. It has significantly less impact on the calling goroutine.

func ConstFormatterV

func ConstFormatterV(k string, v interface{}) Field

ConstFormatterV returns a new Field with the given key and interface to format. It uses the predefined verb "%#v" (a Go-syntax representation of the value).

Call ConstFormatterV if your object is const. It has significantly less impact on the calling goroutine.

func ConstInts

func ConstInts(k string, v []int) Field

ConstInts returns a new Field with the given key and slice of ints.

Call ConstInts if your array is const. It has significantly less impact on the calling goroutine.

func ConstInts16

func ConstInts16(k string, v []int16) Field

ConstInts16 returns a new Field with the given key and slice of 16-bit ints.

Call ConstInts16 if your array is const. It has significantly less impact on the calling goroutine.

func ConstInts32

func ConstInts32(k string, v []int32) Field

ConstInts32 returns a new Field with the given key and slice of 32-bit ints.

Call ConstInts32 if your array is const. It has significantly less impact on the calling goroutine.

func ConstInts64

func ConstInts64(k string, v []int64) Field

ConstInts64 returns a new Field with the given key and slice of 64-bit ints.

Call ConstInts64 if your array is const. It has significantly less impact on the calling goroutine.

func ConstInts8

func ConstInts8(k string, v []int8) Field

ConstInts8 returns a new Field with the given key and slice of 8-bit ints.

Call ConstInts8 if your array is const. It has significantly less impact on the calling goroutine.

func ConstStringer

func ConstStringer(k string, v fmt.Stringer) Field

ConstStringer returns a new Field with the given key and Stringer. Call ConstStringer if your object is const. It has significantly less impact on the calling goroutine.

func ConstUints

func ConstUints(k string, v []uint) Field

ConstUints returns a new Field with the given key and slice of uints.

Call ConstUints if your array is const. It has significantly less impact on the calling goroutine.

func ConstUints16

func ConstUints16(k string, v []uint16) Field

ConstUints16 returns a new Field with the given key and slice of 16-bit uints.

Call ConstUints16 if your array is const. It has significantly less impact on the calling goroutine.

func ConstUints32

func ConstUints32(k string, v []uint32) Field

ConstUints32 returns a new Field with the given key and slice of 32-bit uints.

Call ConstUints32 if your array is const. It has significantly less impact on the calling goroutine.

func ConstUints64

func ConstUints64(k string, v []uint64) Field

ConstUints64 returns a new Field with the given key and slice of 64-bit uints.

Call ConstUints64 if your array is const. It has significantly less impact on the calling goroutine.

func ConstUints8

func ConstUints8(k string, v []uint8) Field

ConstUints8 returns a new Field with the given key and slice of 8-bit uints.

Call ConstUints8 if your array is const. It has significantly less impact on the calling goroutine.

func Duration

func Duration(k string, v time.Duration) Field

Duration returns a new Field with the given key and time.Duration.

func Durations

func Durations(k string, v []time.Duration) Field

Durations returns a new Field with the given key and slice of time.Duration.

func Error

func Error(v error) Field

Error returns a new Field with the given error. Key is 'error'.

func Float32

func Float32(k string, v float32) Field

Float32 returns a new Field with the given key and float32.

func Float64

func Float64(k string, v float64) Field

Float64 returns a new Field with the given key and float64.

func Floats32

func Floats32(k string, v []float32) Field

Floats32 returns a new Field with the given key and slice of 32-bit floats.

func Floats64

func Floats64(k string, v []float64) Field

Floats64 returns a new Field with the given key and slice of 64-biy floats.

func Formatter

func Formatter(k string, verb string, v interface{}) Field

Formatter returns a new Field with the given key, verb and interface to format.

func FormatterV

func FormatterV(k string, v interface{}) Field

FormatterV returns a new Field with the given key and interface to format. It uses the predefined verb "%#v" (a Go-syntax representation of the value).

func Int

func Int(k string, v int) Field

Int returns a new Field with the given key and int.

func Int16

func Int16(k string, v int16) Field

Int16 returns a new Field with the given key and int16.

func Int32

func Int32(k string, v int32) Field

Int32 returns a new Field with the given key and int32.

func Int64

func Int64(k string, v int64) Field

Int64 returns a new Field with the given key and int64.

func Int8

func Int8(k string, v int8) Field

Int8 returns a new Field with the given key and int.8

func Ints

func Ints(k string, v []int) Field

Ints returns a new Field with the given key and slice of ints.

func Ints16

func Ints16(k string, v []int16) Field

Ints16 returns a new Field with the given key and slice of 16-bit ints.

func Ints32

func Ints32(k string, v []int32) Field

Ints32 returns a new Field with the given key and slice of 32-bit ints.

func Ints64

func Ints64(k string, v []int64) Field

Ints64 returns a new Field with the given key and slice of 64-bit ints.

func Ints8

func Ints8(k string, v []int8) Field

Ints8 returns a new Field with the given key and slice of 8-bit ints.

func NamedError

func NamedError(k string, v error) Field

NamedError returns a new Field with the given key and error.

func Object

func Object(k string, v ObjectEncoder) Field

Object returns a new Field with the given key and ObjectEncoder.

func String

func String(k string, v string) Field

String returns a new Field with the given key and string.

func Stringer

func Stringer(k string, v fmt.Stringer) Field

Stringer returns a new Field with the given key and Stringer.

func Strings

func Strings(k string, v []string) Field

Strings returns a new Field with the given key and slice of strings.

func Time

func Time(k string, v time.Time) Field

Time returns a new Field with the given key and time.Time.

func Uint

func Uint(k string, v uint) Field

Uint returns a new Field with the given key and uint.

func Uint16

func Uint16(k string, v uint16) Field

Uint16 returns a new Field with the given key and uint16.

func Uint32

func Uint32(k string, v uint32) Field

Uint32 returns a new Field with the given key and uint32.

func Uint64

func Uint64(k string, v uint64) Field

Uint64 returns a new Field with the given key and uint64.

func Uint8

func Uint8(k string, v uint8) Field

Uint8 returns a new Field with the given key and uint8.

func Uints

func Uints(k string, v []uint) Field

Uints returns a new Field with the given key and slice of uints.

func Uints16

func Uints16(k string, v []uint16) Field

Uints16 returns a new Field with the given key and slice of 16-bit uints.

func Uints32

func Uints32(k string, v []uint32) Field

Uints32 returns a new Field with the given key and slice of 32-bit uints.

func Uints64

func Uints64(k string, v []uint64) Field

Uints64 returns a new Field with the given key and slice of 64-bit uints.

func Uints8

func Uints8(k string, v []uint8) Field

Uints8 returns a new Field with the given key and slice of 8-bit uints.

func (Field) Accept

func (fd Field) Accept(v FieldEncoder)

Accept interprets Field data according to FieldType and calls appropriate FieldEncoder function.

type FieldEncoder

type FieldEncoder interface {
	EncodeFieldAny(string, interface{})
	EncodeFieldBool(string, bool)
	EncodeFieldInt64(string, int64)
	EncodeFieldInt32(string, int32)
	EncodeFieldInt16(string, int16)
	EncodeFieldInt8(string, int8)
	EncodeFieldUint64(string, uint64)
	EncodeFieldUint32(string, uint32)
	EncodeFieldUint16(string, uint16)
	EncodeFieldUint8(string, uint8)
	EncodeFieldFloat64(string, float64)
	EncodeFieldFloat32(string, float32)
	EncodeFieldDuration(string, time.Duration)
	EncodeFieldError(string, error)
	EncodeFieldTime(string, time.Time)
	EncodeFieldString(string, string)
	EncodeFieldBytes(string, []byte)
	EncodeFieldBools(string, []bool)
	EncodeFieldInts64(string, []int64)
	EncodeFieldInts32(string, []int32)
	EncodeFieldInts16(string, []int16)
	EncodeFieldInts8(string, []int8)
	EncodeFieldUints64(string, []uint64)
	EncodeFieldUints32(string, []uint32)
	EncodeFieldUints16(string, []uint16)
	EncodeFieldUints8(string, []uint8)
	EncodeFieldFloats64(string, []float64)
	EncodeFieldFloats32(string, []float32)
	EncodeFieldDurations(string, []time.Duration)
	EncodeFieldArray(string, ArrayEncoder)
	EncodeFieldObject(string, ObjectEncoder)
}

FieldEncoder defines the interface that allows to encode basic types with field names. Encoder companion.

type FieldType

type FieldType byte

FieldType specifies how to handle Field data.

const (
	FieldTypeUnknown FieldType = iota
	FieldTypeAny
	FieldTypeBool
	FieldTypeInt64
	FieldTypeInt32
	FieldTypeInt16
	FieldTypeInt8
	FieldTypeUint64
	FieldTypeUint32
	FieldTypeUint16
	FieldTypeUint8
	FieldTypeFloat64
	FieldTypeFloat32
	FieldTypeDuration
	FieldTypeError
	FieldTypeTime

	FieldTypeBytes
	FieldTypeBytesToString
	FieldTypeBytesToBools
	FieldTypeBytesToInts64
	FieldTypeBytesToInts32
	FieldTypeBytesToInts16
	FieldTypeBytesToInts8
	FieldTypeBytesToUints64
	FieldTypeBytesToUints32
	FieldTypeBytesToUints16
	FieldTypeBytesToUints8
	FieldTypeBytesToFloats64
	FieldTypeBytesToFloats32
	FieldTypeBytesToDurations

	FieldTypeArray
	FieldTypeObject
	FieldTypeStringer
	FieldTypeFormatter
)

Set of FileType values.

const (
	FieldTypeRawMask FieldType = 1<<7 + iota
	FieldTypeRawBytes
	FieldTypeRawBytesToBools
	FieldTypeRawBytesToInts64
	FieldTypeRawBytesToInts32
	FieldTypeRawBytesToInts16
	FieldTypeRawBytesToInts8
	FieldTypeRawBytesToUints64
	FieldTypeRawBytesToUints32
	FieldTypeRawBytesToUints16
	FieldTypeRawBytesToUints8
	FieldTypeRawBytesToFloats64
	FieldTypeRawBytesToFloats32
	FieldTypeRawBytesToDurations
)

Special cases that are processed during snapshoting phase.

type JSONEncoderConfig

type JSONEncoderConfig struct {
	FieldKeyMsg    string
	FieldKeyTime   string
	FieldKeyLevel  string
	FieldKeyName   string
	FieldKeyCaller string

	DisableFieldMsg    bool
	DisableFieldTime   bool
	DisableFieldLevel  bool
	DisableFieldName   bool
	DisableFieldCaller bool

	EncodeTime     TimeEncoder
	EncodeDuration DurationEncoder
	EncodeError    ErrorEncoder
	EncodeLevel    LevelEncoder
	EncodeCaller   CallerEncoder
}

JSONEncoderConfig allows to configure journal JSON Encoder.

func (JSONEncoderConfig) WithDefaults

func (c JSONEncoderConfig) WithDefaults() JSONEncoderConfig

WithDefaults returns the new config in which all uninitialized fields are filled with their default values.

type Level

type Level int8

Level defines severity level of a log message.

const (
	// LevelError allows to log errors only.
	LevelError Level = iota
	// LevelWarning allows to log errors and warnings.
	LevelWarn
	// LevelInfo is the default logging level. Allows to log errors, warnings and infos.
	LevelInfo
	// LevelDebug allows to log messages with all severity levels.
	LevelDebug
)

Severity levels.

func LevelFromString

func LevelFromString(lvl string) (Level, bool)

LevelFromString creates the new Level with the given string.

func (Level) Checker

func (l Level) Checker() LevelChecker

Checker is the common way to get LevelChecker. Use it with every custom implementation of Level.

func (Level) Enabled

func (l Level) Enabled(o Level) bool

Enabled returns true if the given level is allowed within the current level.

func (Level) LevelChecker

func (l Level) LevelChecker() LevelChecker

LevelChecker implements LevelCheckerGetter.

func (Level) String

func (l Level) String() string

String implements fmt.Stringer. String returns a lower-case string representation of the Level.

func (Level) UpperCaseString

func (l Level) UpperCaseString() string

UpperCaseString returns an upper-case string representation of the Level.

type LevelChecker

type LevelChecker func(Level) bool

LevelChecker abstracts level checking process.

type LevelCheckerGetter

type LevelCheckerGetter interface {
	LevelChecker() LevelChecker
}

LevelCheckerGetter allows the implementor to act like a common Level checker for the Logger.

type LevelCheckerGetterFunc

type LevelCheckerGetterFunc func() LevelChecker

LevelCheckerGetterFunc defines a function that returns LevelChecker.

func (LevelCheckerGetterFunc) LevelChecker

func (fn LevelCheckerGetterFunc) LevelChecker() LevelChecker

LevelChecker implements LevelCheckerGetter interface.

type LevelEncoder

type LevelEncoder func(Level, TypeEncoder)

LevelEncoder is the function type to encode Level.

type LogFunc

type LogFunc func(string, ...Field)

LogFunc allows to log a message with a bound level.

type Logger

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

Logger is the fast, asynchronous, structured logger.

The Logger wraps EntryWriter to check logging level and provide a bit of syntactic sugar.

func DisabledLogger

func DisabledLogger() *Logger

DisabledLogger returns a default instance of a Logger that logs nothing as fast as possible.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext returns the Logger associated with this context or nil if no value is associated. Successive calls to FromContext returns the same result.

func NewDisabledLogger

func NewDisabledLogger() *Logger

NewDisabledLogger return a new Logger that logs nothing as fast as possible.

func NewLogger

func NewLogger(level LevelCheckerGetter, w EntryWriter) *Logger

NewLogger returns a new Logger with a given Level and EntryWriter.

func (*Logger) AtLevel

func (l *Logger) AtLevel(lvl Level, fn func(LogFunc))

AtLevel calls the given fn if logging a message at the specified level is enabled, passing a LogFunc with the bound level.

func (*Logger) Debug

func (l *Logger) Debug(text string, fs ...Field)

Debug logs a debug message with the given text, optional fields and fields passed to the Logger using With function.

func (*Logger) Error

func (l *Logger) Error(text string, fs ...Field)

Error logs an error message with the given text, optional fields and fields passed to the Logger using With function.

func (*Logger) Info

func (l *Logger) Info(text string, fs ...Field)

Info logs an info message with the given text, optional fields and fields passed to the Logger using With function.

func (*Logger) Warn

func (l *Logger) Warn(text string, fs ...Field)

Warn logs a warning message with the given text, optional fields and fields passed to the Logger using With function.

func (*Logger) With

func (l *Logger) With(fs ...Field) *Logger

With returns a new Logger with the given additional fields.

func (*Logger) WithCaller

func (l *Logger) WithCaller() *Logger

WithCaller returns a new Logger that adds a special annotation parameters to each logging message, such as the filename and line number of a caller.

func (*Logger) WithCallerSkip

func (l *Logger) WithCallerSkip(skip int) *Logger

WithCallerSkip returns a new Logger with increased number of skipped frames. It's usable to build a custom wrapper for the Logger.

func (*Logger) WithName

func (l *Logger) WithName(n string) *Logger

WithName returns a new Logger adding the given name to the calling one. Name separator is a period.

Loggers has no name by default.

type MutableLevel

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

MutableLevel allows to switch the logging level atomically.

The logger does not allow to change logging level in runtime by itself.

func NewMutableLevel

func NewMutableLevel(l Level) *MutableLevel

NewMutableLevel creates an instance of MutableLevel with the given starting level.

func (*MutableLevel) Checker

func (l *MutableLevel) Checker() LevelChecker

Checker is common way to get LevelChecker. Use it with every custom implementation of Level.

func (*MutableLevel) Level

func (l *MutableLevel) Level() Level

Level returns the current logging level.

func (*MutableLevel) LevelChecker

func (l *MutableLevel) LevelChecker() LevelChecker

LevelChecker implements LevelCheckerGetter.

func (*MutableLevel) Set

func (l *MutableLevel) Set(o Level)

Set switches the current logging level to the given one.

type ObjectEncoder

type ObjectEncoder interface {
	EncodeLogfObject(FieldEncoder) error
}

ObjectEncoder defines the interface to create your own object logger.

Example:

type user struct {
	Username string
	Password string
}

func (u user) EncodeLogfObject(e FieldEncoder) error {
	e.EncodeFieldString("username", u.Username)
	e.EncodeFieldString("password", u.Password)

	return nil
}

type Snapshotter

type Snapshotter interface {
	TakeSnapshot() interface{}
}

Snapshotter is the interface that allows to do a custom copy of a logging object. If the object type implements TaskSnapshot function it will be called during the logging procedure in a caller's goroutine.

type TimeEncoder

type TimeEncoder func(time.Time, TypeEncoder)

TimeEncoder is the function type to encode the given Time.

func LayoutTimeEncoder

func LayoutTimeEncoder(layout string) TimeEncoder

LayoutTimeEncoder encodes the given Time as a string using custom layout.

type TypeEncoder

type TypeEncoder interface {
	EncodeTypeAny(interface{})
	EncodeTypeBool(bool)
	EncodeTypeInt64(int64)
	EncodeTypeInt32(int32)
	EncodeTypeInt16(int16)
	EncodeTypeInt8(int8)
	EncodeTypeUint64(uint64)
	EncodeTypeUint32(uint32)
	EncodeTypeUint16(uint16)
	EncodeTypeUint8(uint8)
	EncodeTypeFloat64(float64)
	EncodeTypeFloat32(float32)
	EncodeTypeDuration(time.Duration)
	EncodeTypeTime(time.Time)
	EncodeTypeString(string)
	EncodeTypeBytes([]byte)
	EncodeTypeBools([]bool)
	EncodeTypeInts64([]int64)
	EncodeTypeInts32([]int32)
	EncodeTypeInts16([]int16)
	EncodeTypeInts8([]int8)
	EncodeTypeUints64([]uint64)
	EncodeTypeUints32([]uint32)
	EncodeTypeUints16([]uint16)
	EncodeTypeUints8([]uint8)
	EncodeTypeFloats64([]float64)
	EncodeTypeFloats32([]float32)
	EncodeTypeDurations([]time.Duration)
	EncodeTypeArray(ArrayEncoder)
	EncodeTypeObject(ObjectEncoder)
	EncodeTypeUnsafeBytes(unsafe.Pointer)
}

TypeEncoder defines the interface that allows to encode basic types. Encoder companion.

type TypeEncoderFactory

type TypeEncoderFactory interface {
	TypeEncoder(*Buffer) TypeEncoder
}

TypeEncoderFactory defines the interface that allows to reuse Encoder internal-defined TypeEncoder in other encoder.

E.g. logf json encoder implements TypeEncoderFactory allowing all other encoders to use json encoding functionality in some cases.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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