rz

package module
v2.6.1 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2019 License: Apache-2.0 Imports: 16 Imported by: 0

README

rz

RipZap - The fastest structured, leveled JSON logger for Go ⚡️. Dependency free.


Make logging great again

GoDoc GitHub release

Console logging

The rz package provides a fast and simple logger dedicated to JSON output avoiding allocations and reflection..

Uber's zap and rs's zerolog libraries pioneered this approach.

ripzap is an update of zerolog taking this concept to the next level with a simpler to use and safer API and even better performance.

To keep the code base and the API simple, ripzap focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) Formatters.

  1. Quickstart
  2. Configuration
  3. Field types
  4. HTTP Handler
  5. Examples
  6. Benchmarks
  7. Versions
  8. Contributing
  9. License

Quickstart

rz requires Go modules so you need a go.mod file at the root of your project.

package main

import (
	"os"

	"github.com/bloom42/rz-go/v2"
	"github.com/bloom42/rz-go/v2/log"
)

func main() {

	env := os.Getenv("GO_ENV")
	hostname, _ := os.Hostname()

	// update global logger's context fields
	log.SetLogger(log.With(rz.Fields(
		rz.String("hostname", hostname), rz.String("environment", env),
	)))

	if env == "production" {
		log.SetLogger(log.With(rz.Level(rz.InfoLevel)))
	}

	log.Info("info from logger", rz.String("hello", "world"))
	// {"level":"info","hostname":"","environment":"","hello":"world","timestamp":"2019-02-07T09:30:07Z","message":"info from logger"}
}

Configuration

Logger

// Writer update logger's writer.
func Writer(writer io.Writer) LoggerOption {}
// Level update logger's level.
func Level(lvl LogLevel) LoggerOption {}
// Sampler update logger's sampler.
func Sampler(sampler LogSampler) LoggerOption {}
// AddHook appends hook to logger's hook
func AddHook(hook LogHook) LoggerOption {}
// Hooks replaces logger's hooks
func Hooks(hooks ...LogHook) LoggerOption {}
// With replaces logger's context fields
func With(fields func(*Event)) LoggerOption {}
// Stack enable/disable stack in error messages.
func Stack(enableStack bool) LoggerOption {}
// Timestamp enable/disable timestamp logging in error messages.
func Timestamp(enableTimestamp bool) LoggerOption {}
// Caller enable/disable caller field in message messages.
func Caller(enableCaller bool) LoggerOption {}
// Formatter update logger's formatter.
func Formatter(formatter LogFormatter) LoggerOption {}
// TimestampFieldName update logger's timestampFieldName.
func TimestampFieldName(timestampFieldName string) LoggerOption {}
// LevelFieldName update logger's levelFieldName.
func LevelFieldName(levelFieldName string) LoggerOption {}
// MessageFieldName update logger's messageFieldName.
func MessageFieldName(messageFieldName string) LoggerOption {}
// ErrorFieldName update logger's errorFieldName.
func ErrorFieldName(errorFieldName string) LoggerOption {}
// CallerFieldName update logger's callerFieldName.
func CallerFieldName(callerFieldName string) LoggerOption {}
// CallerSkipFrameCount update logger's callerSkipFrameCount.
func CallerSkipFrameCount(callerSkipFrameCount int) LoggerOption {}
// ErrorStackFieldName update logger's errorStackFieldName.
func ErrorStackFieldName(errorStackFieldName string) LoggerOption {}
// TimeFieldFormat update logger's timeFieldFormat.
func TimeFieldFormat(timeFieldFormat string) LoggerOption {}
// TimestampFunc update logger's timestampFunc.
func TimestampFunc(timestampFunc func() time.Time) LoggerOption {}

Global

var (
	// DurationFieldUnit defines the unit for time.Duration type fields added
	// using the Duration method.
	DurationFieldUnit = time.Millisecond

	// DurationFieldInteger renders Duration fields as integer instead of float if
	// set to true.
	DurationFieldInteger = false

	// ErrorHandler is called whenever rz fails to write an event on its
	// output. If not set, an error is printed on the stderr. This handler must
	// be thread safe and non-blocking.
	ErrorHandler func(err error)
)

Field Types

Standard Types

  • String
  • Bool
  • Int, Int8, Int16, Int32, Int64
  • Uint, Uint8, Uint16, Uint32, Uint64
  • Float32, Float64

Advanced Fields

  • Err: Takes an error and render it as a string using the logger.errorFieldName field name.
  • Error: Adds a field with a error.
  • Timestamp: Insert a timestamp field with logger.timestampFieldName field name and formatted using logger.timeFieldFormat.
  • Time: Adds a field with the time formated with the logger.timeFieldFormat.
  • Duration: Adds a field with a time.Duration.
  • Dict: Adds a sub-key/value as a field of the event.
  • Interface: Uses reflection to marshal the type.

HTTP Handler

See the bloom42/rz-go/rzhttp package or the example here.

Examples

See the examples folder.

Benchmarks

See Logbench

or

$ make benchmarks

Note that data may be biased, see http://hackemist.com/logbench/ for more details

Versions

For v2 (current) see the master branch.

For v1 see the v1 branch.

Contributing

See https://bloom.sh/contribute

License

See LICENSE.txt and https://bloom.sh/licensing

From an original work by rs: zerolog - commit aa55558e4cb2e8f05cd079342d430f77e946d00a

Documentation

Overview

Package rz provides a lightweight logging library dedicated to JSON logging.

A global Logger can be use for simple logging:

import "github.com/bloom42/rz-go/v2/log"

log.Info("hello world")

// Output: {"timestamp":"2019-02-07T09:30:07Z","level":"info","message":"hello world"}

NOTE: To import the global logger, import the "log" subpackage "github.com/bloom42/rz-go/v2/log".

Fields can be added to log messages:

log.Info("hello world", rz.String("foo", "bar"))

// Output: {"timestamp":"2019-02-07T09:30:07Z","level":"info","message":"hello world","foo":"bar"}

Create logger instance to manage different outputs:

logger := rz.New()
log.Info("hello world",rz.String("foo", "bar"))

// Output: {"timestamp":"2019-02-07T09:30:07Z","level":"info","message":"hello world","foo":"bar"}

Sub-loggers let you chain loggers with additional context:

sublogger := log.Config(rz.With(rz.String("component": "foo")))
sublogger.Info("hello world", nil)

// Output: {"timestamp":"2019-02-07T09:30:07Z","level":"info","message":"hello world","component":"foo"}

Index

Examples

Constants

View Source
const (
	// DefaultTimestampFieldName is the default field name used for the timestamp field.
	DefaultTimestampFieldName = "timestamp"

	// DefaultLevelFieldName is the default field name used for the level field.
	DefaultLevelFieldName = "level"

	// DefaultMessageFieldName is the default field name used for the message field.
	DefaultMessageFieldName = "message"

	// DefaultErrorFieldName is the default field name used for error fields.
	DefaultErrorFieldName = "error"

	// DefaultCallerFieldName is the default field name used for caller field.
	DefaultCallerFieldName = "caller"

	// DefaultCallerSkipFrameCount is the default number of stack frames to skip to find the caller.
	DefaultCallerSkipFrameCount = 3

	// DefaultErrorStackFieldName is the default field name used for error stacks.
	DefaultErrorStackFieldName = "stack"

	// DefaultTimeFieldFormat defines the time format of the Time field type.
	// If set to an empty string, the time is formatted as an UNIX timestamp
	// as integer.
	DefaultTimeFieldFormat = time.RFC3339
)
View Source
const (
	// SampleOften samples log every ~ 10 events.
	SampleOften = SamplerRandom(10)
	// SampleSometimes samples log every ~ 100 events.
	SampleSometimes = SamplerRandom(100)
	// SampleRarely samples log every ~ 1000 events.
	SampleRarely = SamplerRandom(1000)
)
View Source
const (
	// Version is the library's version
	Version = "2.6.1"
)

Variables

View Source
var (
	// DurationFieldUnit defines the unit for time.Duration type fields added
	// using the Duration method.
	DurationFieldUnit = time.Millisecond

	// DurationFieldInteger renders Dur fields as integer instead of float if
	// set to true.
	DurationFieldInteger = false

	// ErrorHandler is called whenever rz fails to write an event on its
	// output. If not set, an error is printed on the stderr. This handler must
	// be thread safe and non-blocking.
	ErrorHandler func(err error)

	// ErrorStackMarshaler extract the stack from err if any.
	ErrorStackMarshaler func(err error) interface{}

	// ErrorMarshalFunc allows customization of global error marshaling
	ErrorMarshalFunc = func(err error) interface{} {
		return err
	}
)
View Source
var (
	// DefaultTimestampFunc defines default the function called to generate a timestamp.
	DefaultTimestampFunc func() time.Time = func() time.Time { return time.Now().UTC() }
)

Functions

func SyncWriter

func SyncWriter(w io.Writer) io.Writer

SyncWriter wraps w so that each call to Write is synchronized with a mutex. This syncer can be the call to writer's Write method is not thread safe. Note that os.File Write operation is using write() syscall which is supposed to be thread-safe on POSIX systems. So there is no need to use this with os.File on such systems as rz guaranties to issue a single Write call per log event.

Types

type Encoder

type Encoder interface {
	AppendArrayDelim(dst []byte) []byte
	AppendArrayEnd(dst []byte) []byte
	AppendArrayStart(dst []byte) []byte
	AppendBeginMarker(dst []byte) []byte
	AppendBool(dst []byte, val bool) []byte
	AppendBools(dst []byte, vals []bool) []byte
	AppendBytes(dst, s []byte) []byte
	AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte
	AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte
	AppendEndMarker(dst []byte) []byte
	AppendFloat32(dst []byte, val float32) []byte
	AppendFloat64(dst []byte, val float64) []byte
	AppendFloats32(dst []byte, vals []float32) []byte
	AppendFloats64(dst []byte, vals []float64) []byte
	AppendHex(dst, s []byte) []byte
	AppendIPAddr(dst []byte, ip net.IP) []byte
	AppendIPPrefix(dst []byte, pfx net.IPNet) []byte
	AppendInt(dst []byte, val int) []byte
	AppendInt16(dst []byte, val int16) []byte
	AppendInt32(dst []byte, val int32) []byte
	AppendInt64(dst []byte, val int64) []byte
	AppendInt8(dst []byte, val int8) []byte
	AppendInterface(dst []byte, i interface{}) []byte
	AppendInts(dst []byte, vals []int) []byte
	AppendInts16(dst []byte, vals []int16) []byte
	AppendInts32(dst []byte, vals []int32) []byte
	AppendInts64(dst []byte, vals []int64) []byte
	AppendInts8(dst []byte, vals []int8) []byte
	AppendKey(dst []byte, key string) []byte
	AppendLineBreak(dst []byte) []byte
	AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte
	AppendNil(dst []byte) []byte
	AppendObjectData(dst []byte, o []byte) []byte
	AppendString(dst []byte, s string) []byte
	AppendStrings(dst []byte, vals []string) []byte
	AppendTime(dst []byte, t time.Time, format string) []byte
	AppendTimes(dst []byte, vals []time.Time, format string) []byte
	AppendUint(dst []byte, val uint) []byte
	AppendUint16(dst []byte, val uint16) []byte
	AppendUint32(dst []byte, val uint32) []byte
	AppendUint64(dst []byte, val uint64) []byte
	AppendUint8(dst []byte, val uint8) []byte
	AppendUints(dst []byte, vals []uint) []byte
	AppendUints16(dst []byte, vals []uint16) []byte
	AppendUints32(dst []byte, vals []uint32) []byte
	AppendUints64(dst []byte, vals []uint64) []byte
	AppendUints8(dst []byte, vals []uint8) []byte
}

Encoder is used to serialize an object to be logged

type Event

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

Event represents a log event. It is instanced by one of the level method.

func (*Event) Append

func (e *Event) Append(fields ...Field)

Append the given fields to the event

func (*Event) Enabled

func (e *Event) Enabled() bool

Enabled return false if the *Event is going to be filtered out by log level or sampling.

func (*Event) Fields added in v2.6.0

func (e *Event) Fields() (map[string]interface{}, error)

Fields returns the fields from the event. Note that this call is very expensive and should be used sparingly.

type Field

type Field func(e *Event)

Field functions are used to add fields to events

func Any

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

Any adds the field key with i marshaled using reflection.

func Bool

func Bool(key string, value bool) Field

Bool adds the field key with i as a bool to the *Event context.

func Bools

func Bools(key string, value []bool) Field

Bools adds the field key with i as a []bool to the *Event context.

func Bytes

func Bytes(key string, value []byte) Field

Bytes adds the field key with val as a string to the *Event context.

Runes outside of normal ASCII ranges will be hex-encoded in the resulting JSON.

func Caller

func Caller(enable bool) Field

Caller adds the file:line of the caller with the rz.CallerFieldName key.

func Dict

func Dict(key string, value *Event) Field

Dict adds the field key with a dict to the event context. Use rz.Dict() to create the dictionary.

func Discard

func Discard() Field

Discard disables the event

func Duration

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

Duration adds the field key with duration d stored as rz.DurationFieldUnit. If rz.DurationFieldInteger is true, durations are rendered as integer instead of float.

func Durations

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

Durations adds the field key with duration d stored as rz.DurationFieldUnit. If rz.DurationFieldInteger is true, durations are rendered as integer instead of float.

func EmbedObject

func EmbedObject(obj LogObjectMarshaler) Field

EmbedObject marshals an object that implement the LogObjectMarshaler interface.

func Err

func Err(value error) Field

Err adds the field "error" with serialized err to the *Event context. If err is nil, no field is added. To customize the key name, uze rz.ErrorFieldName.

If Stack() has been called before and rz.ErrorStackMarshaler is defined, the err is passed to ErrorStackMarshaler and the result is appended to the rz.ErrorStackFieldName.

func Error

func Error(key string, value error) Field

Error adds the field key with serialized err to the *Event context. If err is nil, no field is added.

func Errors

func Errors(key string, value []error) Field

Errors adds the field key with errs as an array of serialized errors to the *Event context.

func Float32

func Float32(key string, value float32) Field

Float32 adds the field key with f as a float32 to the *Event context.

func Float64

func Float64(key string, value float64) Field

Float64 adds the field key with f as a float64 to the *Event context.

func Floats32

func Floats32(key string, value []float32) Field

Floats32 adds the field key with f as a []float32 to the *Event context.

func Floats64

func Floats64(key string, value []float64) Field

Floats64 adds the field key with f as a []float64 to the *Event context.

func HardwareAddr

func HardwareAddr(key string, value net.HardwareAddr) Field

HardwareAddr adds HardwareAddr to the event

func Hex

func Hex(key string, value []byte) Field

Hex adds the field key with val as a hex string to the *Event context.

func IP

func IP(key string, value net.IP) Field

IP adds IPv4 or IPv6 Address to the event

func IPNet

func IPNet(key string, value net.IPNet) Field

IPNet adds IPv4 or IPv6 Prefix (address and mask) to the event

func Int

func Int(key string, value int) Field

Int adds the field key with i as a int to the *Event context.

func Int16

func Int16(key string, value int16) Field

Int16 adds the field key with i as a int16 to the *Event context.

func Int32

func Int32(key string, value int32) Field

Int32 adds the field key with i as a int32 to the *Event context.

func Int64

func Int64(key string, value int64) Field

Int64 adds the field key with i as a int64 to the *Event context.

func Int8

func Int8(key string, value int8) Field

Int8 adds the field key with i as a int8 to the *Event context.

func Ints

func Ints(key string, value []int) Field

Ints adds the field key with i as a []int to the *Event context.

func Ints16

func Ints16(key string, value []int16) Field

Ints16 adds the field key with i as a []int16 to the *Event context.

func Ints32

func Ints32(key string, value []int32) Field

Ints32 adds the field key with i as a []int32 to the *Event context.

func Ints64

func Ints64(key string, value []int64) Field

Ints64 adds the field key with i as a []int64 to the *Event context.

func Ints8

func Ints8(key string, value []int8) Field

Ints8 adds the field key with i as a []int8 to the *Event context.

func Map

func Map(fields map[string]interface{}) Field

Map is a helper function to use a map to set fields using type assertion.

func Object

func Object(key string, value LogObjectMarshaler) Field

Object marshals an object that implement the LogObjectMarshaler interface.

func RawJSON

func RawJSON(key string, value []byte) Field

RawJSON adds already encoded JSON to the log line under key.

No sanity check is performed on b; it must not contain carriage returns and be valid JSON.

func Stack

func Stack(enable bool) Field

Stack enables stack trace printing for the error passed to Err().

logger.errorStackMarshaler must be set for this method to do something.

func String

func String(key, value string) Field

String adds the field key with val as a string to the *Event context.

func Strings

func Strings(key string, value []string) Field

Strings adds the field key with vals as a []string to the *Event context.

func Time

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

Time adds the field key with t formated as string using rz.TimeFieldFormat.

func Times

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

Times adds the field key with t formated as string using rz.TimeFieldFormat.

func Timestamp

func Timestamp(enable bool) Field

Timestamp adds the current local time as UNIX timestamp to the *Event context with the logger.TimestampFieldName key.

func Uint

func Uint(key string, value uint) Field

Uint adds the field key with i as a uint to the *Event context.

func Uint16

func Uint16(key string, value uint16) Field

Uint16 adds the field key with i as a uint16 to the *Event context.

func Uint32

func Uint32(key string, value uint32) Field

Uint32 adds the field key with i as a uint32 to the *Event context.

func Uint64

func Uint64(key string, value uint64) Field

Uint64 adds the field key with i as a uint64 to the *Event context.

func Uint8

func Uint8(key string, value uint8) Field

Uint8 adds the field key with i as a uint8 to the *Event context.

func Uints

func Uints(key string, value []uint) Field

Uints adds the field key with i as a []uint to the *Event context.

func Uints16

func Uints16(key string, value []uint16) Field

Uints16 adds the field key with i as a []uint16 to the *Event context.

func Uints32

func Uints32(key string, value []uint32) Field

Uints32 adds the field key with i as a []uint32 to the *Event context.

func Uints64

func Uints64(key string, value []uint64) Field

Uints64 adds the field key with i as a []uint64 to the *Event context.

func Uints8

func Uints8(key string, value []uint8) Field

Uints8 adds the field key with i as a []uint8 to the *Event context.

type HookFunc

type HookFunc func(e *Event, level LogLevel, message string)

HookFunc is an adaptor to allow the use of an ordinary function as a LogHook.

func (HookFunc) Run

func (h HookFunc) Run(e *Event, level LogLevel, message string)

Run implements the Hook interface.

type LevelHook

type LevelHook struct {
	NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook LogHook
}

LevelHook applies a different hook for each level.

func NewLevelHook

func NewLevelHook() LevelHook

NewLevelHook returns a new LevelHook.

func (LevelHook) Run

func (h LevelHook) Run(e *Event, level LogLevel, message string)

Run implements the Hook interface.

type LevelWriter

type LevelWriter interface {
	io.Writer
	WriteLevel(level LogLevel, p []byte) (n int, err error)
}

LevelWriter defines as interface a writer may implement in order to receive level information with payload.

func MultiLevelWriter

func MultiLevelWriter(writers ...io.Writer) LevelWriter

MultiLevelWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command. If some writers implement LevelWriter, their WriteLevel method will be used instead of Write.

type LogFormatter

type LogFormatter func(ev *Event) ([]byte, error)

LogFormatter can be used to log to another format than JSON

func FormatterCLI

func FormatterCLI() LogFormatter

FormatterCLI prettify output suitable for command-line interfaces.

func FormatterConsole

func FormatterConsole() LogFormatter

FormatterConsole prettify output for human cosumption

func FormatterLogfmt

func FormatterLogfmt() LogFormatter

FormatterLogfmt prettify output for human consumption, using the logfmt format.

type LogHook

type LogHook interface {
	// Run runs the hook with the event.
	Run(e *Event, level LogLevel, message string)
}

LogHook defines an interface to a log hook.

type LogLevel

type LogLevel uint8

LogLevel defines log levels.

const (
	// DebugLevel defines debug log level.
	DebugLevel LogLevel = iota
	// InfoLevel defines info log level.
	InfoLevel
	// WarnLevel defines warn log level.
	WarnLevel
	// ErrorLevel defines error log level.
	ErrorLevel
	// FatalLevel defines fatal log level.
	FatalLevel
	// PanicLevel defines panic log level.
	PanicLevel
	// NoLevel defines an absent log level.
	NoLevel
	// Disabled disables the logger.
	Disabled
)

func ParseLevel

func ParseLevel(levelStr string) (LogLevel, error)

ParseLevel converts a level string into a rz Level value. returns an error if the input string does not match known values.

func (LogLevel) String

func (l LogLevel) String() string

type LogObjectMarshaler

type LogObjectMarshaler interface {
	MarshalRzObject(*Event)
}

LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Object methods.

type LogSampler

type LogSampler interface {
	// Sample returns true if the event should be part of the sample, false if
	// the event should be dropped.
	Sample(lvl LogLevel) bool
}

LogSampler defines an interface to a log sampler.

type Logger

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

A Logger represents an active logging object that generates lines of JSON output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. There is no guaranty on access serialization to the Writer. If your Writer is not thread safe, you may consider a sync wrapper.

func FromCtx

func FromCtx(ctx context.Context) *Logger

FromCtx returns the Logger associated with the ctx. If no logger is associated, a New() logger is returned with a addedfield "rz.FromCtx": "error".

For example, to add a field to an existing logger in the context, use this notation:

ctx := r.Context()
l := rz.FromCtx(ctx)
l.With(...)

func New

func New(options ...LoggerOption) Logger

New creates a root logger with given options. If the output writer implements the LevelWriter interface, the WriteLevel method will be called instead of the Write one. Default writer is os.Stdout

Each logging operation makes a single call to the Writer's Write method. There is no guaranty on access serialization to the Writer. If your Writer is not thread safe, you may consider using sync wrapper.

Example
log := rz.New(rz.Fields(rz.Timestamp(false)))

log.Info("hello world")
Output:

{"level":"info","message":"hello world"}

func Nop

func Nop() Logger

Nop returns a disabled logger for which all operation are no-op.

func (*Logger) Append

func (l *Logger) Append(fields ...Field)

Append the fields to the internal logger's context. It does not create a noew copy of the logger and rely on a mutex to enable thread safety, so `With(Fields(fields...))` often is preferable.

func (*Logger) Debug

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

Debug logs a new message with debug level.

func (*Logger) Error

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

Error logs a message with error level.

func (*Logger) Fatal

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

Fatal logs a new message with fatal level. The os.Exit(1) function is then called, which terminates the program immediately.

func (*Logger) GetLevel added in v2.5.0

func (l *Logger) GetLevel() LogLevel

GetLevel returns the current log level.

func (*Logger) Info

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

Info logs a new message with info level.

func (*Logger) Log

func (l *Logger) Log(message string, fields ...Field)

Log logs a new message with no level. Setting GlobalLevel to Disabled will still disable events produced by this method.

func (*Logger) LogWithLevel added in v2.6.1

func (l *Logger) LogWithLevel(level LogLevel, message string, fields ...Field)

LogWithLevel logs a new message with the given level.

func (*Logger) NewDict

func (l *Logger) NewDict(fields ...Field) *Event

NewDict creates an Event to be used with the Dict method. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.

func (*Logger) Panic

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

Panic logs a new message with panic level. The panic() function is then called, which stops the ordinary flow of a goroutine.

func (*Logger) ToCtx

func (l *Logger) ToCtx(ctx context.Context) context.Context

ToCtx returns a copy of ctx with l associated. If an instance of Logger is already in the context, the context is not updated.

func (*Logger) Warn

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

Warn logs a new message with warn level.

func (Logger) With

func (l Logger) With(options ...LoggerOption) Logger

With create a new copy of the logger and apply all the options to the new logger

func (Logger) Write

func (l Logger) Write(p []byte) (n int, err error)

Write implements the io.Writer interface. This is useful to set as a writer for the standard library log.

log := rz.New()
stdlog.SetFlags(0)
stdlog.SetOutput(log)
stdlog.Print("hello world")

type LoggerOption

type LoggerOption func(logger *Logger)

LoggerOption is used to configure a logger.

func AddHook

func AddHook(hook LogHook) LoggerOption

AddHook appends hook to logger's hook

func CallerFieldName

func CallerFieldName(callerFieldName string) LoggerOption

CallerFieldName update logger's callerFieldName.

func CallerSkipFrameCount

func CallerSkipFrameCount(callerSkipFrameCount int) LoggerOption

CallerSkipFrameCount update logger's callerSkipFrameCount.

func ErrorFieldName

func ErrorFieldName(errorFieldName string) LoggerOption

ErrorFieldName update logger's errorFieldName.

func ErrorStackFieldName

func ErrorStackFieldName(errorStackFieldName string) LoggerOption

ErrorStackFieldName update logger's errorStackFieldName.

func Fields

func Fields(fields ...Field) LoggerOption

Fields update logger's context fields

Example
log := rz.New(rz.Fields(rz.Timestamp(false), rz.String("foo", "bar")))

log.Info("hello world")
Output:

{"level":"info","foo":"bar","message":"hello world"}

func Formatter

func Formatter(formatter LogFormatter) LoggerOption

Formatter update logger's formatter.

func Hooks

func Hooks(hooks ...LogHook) LoggerOption

Hooks replaces logger's hooks

func Level

func Level(lvl LogLevel) LoggerOption

Level update logger's level.

func LevelFieldName

func LevelFieldName(levelFieldName string) LoggerOption

LevelFieldName update logger's levelFieldName.

func MessageFieldName

func MessageFieldName(messageFieldName string) LoggerOption

MessageFieldName update logger's messageFieldName.

func Sampler

func Sampler(sampler LogSampler) LoggerOption

Sampler update logger's sampler.

func TimeFieldFormat

func TimeFieldFormat(timeFieldFormat string) LoggerOption

TimeFieldFormat update logger's timeFieldFormat.

func TimestampFieldName

func TimestampFieldName(timestampFieldName string) LoggerOption

TimestampFieldName update logger's timestampFieldName.

func TimestampFunc

func TimestampFunc(timestampFunc func() time.Time) LoggerOption

TimestampFunc update logger's timestampFunc.

func Writer

func Writer(writer io.Writer) LoggerOption

Writer update logger's writer.

type SamplerBasic

type SamplerBasic struct {
	N uint32
	// contains filtered or unexported fields
}

SamplerBasic is a sampler that will send every Nth events, regardless of there level.

func (*SamplerBasic) Sample

func (s *SamplerBasic) Sample(lvl LogLevel) bool

Sample implements the Sampler interface.

type SamplerBurst

type SamplerBurst struct {
	// Burst is the maximum number of event per period allowed before calling
	// NextSampler.
	Burst uint32
	// Period defines the burst period. If 0, NextSampler is always called.
	Period time.Duration
	// NextSampler is the sampler used after the burst is reached. If nil,
	// events are always rejected after the burst.
	NextSampler LogSampler
	// contains filtered or unexported fields
}

SamplerBurst lets Burst events pass per Period then pass the decision to NextSampler. If Sampler is not set, all subsequent events are rejected.

func (*SamplerBurst) Sample

func (s *SamplerBurst) Sample(lvl LogLevel) bool

Sample implements the Sampler interface.

type SamplerLevel

type SamplerLevel struct {
	DebugSampler LogSampler
	InfoSampler  LogSampler
	WarnSampler  LogSampler
	ErrorSampler LogSampler
}

SamplerLevel applies a different sampler for each level.

func (SamplerLevel) Sample

func (s SamplerLevel) Sample(lvl LogLevel) bool

Sample implements the Sampler interface.

type SamplerRandom

type SamplerRandom uint32

SamplerRandom use a PRNG to randomly sample an event out of N events, regardless of their level.

func (SamplerRandom) Sample

func (s SamplerRandom) Sample(lvl LogLevel) bool

Sample implements the Sampler interface.

Directories

Path Synopsis
examples
internal
Package log provides a global logger for rz.
Package log provides a global logger for rz.
Package rzhttp provides an helper middleware to log HTTP requests See https://github.com/bloom42/rz-go/tree/master/examples/http for a working example
Package rzhttp provides an helper middleware to log HTTP requests See https://github.com/bloom42/rz-go/tree/master/examples/http for a working example

Jump to

Keyboard shortcuts

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