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/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/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 ¶
- Constants
- Variables
- func SyncWriter(w io.Writer) io.Writer
- type Encoder
- type Event
- type Field
- func Any(key string, value interface{}) Field
- func Bool(key string, value bool) Field
- func Bools(key string, value []bool) Field
- func Bytes(key string, value []byte) Field
- func Caller(enable bool) Field
- func Dict(key string, value *Event) Field
- func Discard() Field
- func Duration(key string, value time.Duration) Field
- func Durations(key string, value []time.Duration) Field
- func EmbedObject(obj LogObjectMarshaler) Field
- func Err(value error) Field
- func Error(key string, value error) Field
- func Errors(key string, value []error) Field
- func Float32(key string, value float32) Field
- func Float64(key string, value float64) Field
- func Floats32(key string, value []float32) Field
- func Floats64(key string, value []float64) Field
- func HardwareAddr(key string, value net.HardwareAddr) Field
- func Hex(key string, value []byte) Field
- func IP(key string, value net.IP) Field
- func IPNet(key string, value net.IPNet) Field
- func Int(key string, value int) Field
- func Int16(key string, value int16) Field
- func Int32(key string, value int32) Field
- func Int64(key string, value int64) Field
- func Int8(key string, value int8) Field
- func Ints(key string, value []int) Field
- func Ints16(key string, value []int16) Field
- func Ints32(key string, value []int32) Field
- func Ints64(key string, value []int64) Field
- func Ints8(key string, value []int8) Field
- func Map(fields map[string]interface{}) Field
- func Object(key string, value LogObjectMarshaler) Field
- func RawJSON(key string, value []byte) Field
- func Stack(enable bool) Field
- func String(key, value string) Field
- func Strings(key string, value []string) Field
- func Time(key string, value time.Time) Field
- func Times(key string, value []time.Time) Field
- func Timestamp(enable bool) Field
- func Uint(key string, value uint) Field
- func Uint16(key string, value uint16) Field
- func Uint32(key string, value uint32) Field
- func Uint64(key string, value uint64) Field
- func Uint8(key string, value uint8) Field
- func Uints(key string, value []uint) Field
- func Uints16(key string, value []uint16) Field
- func Uints32(key string, value []uint32) Field
- func Uints64(key string, value []uint64) Field
- func Uints8(key string, value []uint8) Field
- type HookFunc
- type LevelHook
- type LevelWriter
- type LogFormatter
- type LogHook
- type LogLevel
- type LogObjectMarshaler
- type LogSampler
- type Logger
- func (l *Logger) Append(fields ...Field)
- func (l *Logger) Debug(message string, fields ...Field)
- func (l *Logger) Error(message string, fields ...Field)
- func (l *Logger) Fatal(message string, fields ...Field)
- func (l *Logger) GetLevel() LogLevel
- func (l *Logger) Info(message string, fields ...Field)
- func (l *Logger) Log(message string, fields ...Field)
- func (l *Logger) LogWithLevel(level LogLevel, message string, fields ...Field)
- func (l *Logger) NewDict(fields ...Field) *Event
- func (l *Logger) Panic(message string, fields ...Field)
- func (l *Logger) ToCtx(ctx context.Context) context.Context
- func (l *Logger) Warn(message string, fields ...Field)
- func (l Logger) With(options ...LoggerOption) Logger
- func (l Logger) Write(p []byte) (n int, err error)
- type LoggerOption
- func AddHook(hook LogHook) LoggerOption
- func CallerFieldName(callerFieldName string) LoggerOption
- func CallerSkipFrameCount(callerSkipFrameCount int) LoggerOption
- func ErrorFieldName(errorFieldName string) LoggerOption
- func ErrorStackFieldName(errorStackFieldName string) LoggerOption
- func Fields(fields ...Field) LoggerOption
- func Formatter(formatter LogFormatter) LoggerOption
- func Hooks(hooks ...LogHook) LoggerOption
- func Level(lvl LogLevel) LoggerOption
- func LevelFieldName(levelFieldName string) LoggerOption
- func MessageFieldName(messageFieldName string) LoggerOption
- func Sampler(sampler LogSampler) LoggerOption
- func TimeFieldFormat(timeFieldFormat string) LoggerOption
- func TimestampFieldName(timestampFieldName string) LoggerOption
- func TimestampFunc(timestampFunc func() time.Time) LoggerOption
- func Writer(writer io.Writer) LoggerOption
- type SamplerBasic
- type SamplerBurst
- type SamplerLevel
- type SamplerRandom
Examples ¶
Constants ¶
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 )
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) )
const (
// Version is the library's version
Version = "1.3.2"
)
Variables ¶
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 } )
Functions ¶
func SyncWriter ¶ added in v0.13.4
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 ¶ added in v1.3.2
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.
type Field ¶ added in v1.3.2
type Field func(e *Event)
Field functions are used to add fields to events
func Bytes ¶ added in v1.3.2
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 ¶ added in v0.13.10
Caller adds the file:line of the caller with the rz.CallerFieldName key.
func Dict ¶ added in v0.13.4
Dict adds the field key with a dict to the event context. Use rz.Dict() to create the dictionary.
func Duration ¶ added in v1.1.0
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 ¶ added in v1.3.2
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 ¶ added in v1.3.2
func EmbedObject(obj LogObjectMarshaler) Field
EmbedObject marshals an object that implement the LogObjectMarshaler interface.
func Err ¶ added in v1.3.2
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 ¶ added in v1.3.2
Error adds the field key with serialized err to the *Event context. If err is nil, no field is added.
func Errors ¶ added in v1.3.2
Errors adds the field key with errs as an array of serialized errors to the *Event context.
func Float32 ¶ added in v1.3.2
Float32 adds the field key with f as a float32 to the *Event context.
func Float64 ¶ added in v1.3.2
Float64 adds the field key with f as a float64 to the *Event context.
func Floats32 ¶ added in v1.3.2
Floats32 adds the field key with f as a []float32 to the *Event context.
func Floats64 ¶ added in v1.3.2
Floats64 adds the field key with f as a []float64 to the *Event context.
func HardwareAddr ¶ added in v1.3.2
func HardwareAddr(key string, value net.HardwareAddr) Field
HardwareAddr adds HardwareAddr to the event
func Map ¶ added in v1.3.2
Map is a helper function to use a map to set fields using type assertion.
func Object ¶ added in v1.3.2
func Object(key string, value LogObjectMarshaler) Field
Object marshals an object that implement the LogObjectMarshaler interface.
func RawJSON ¶ added in v1.3.2
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 ¶ added in v0.13.4
Stack enables stack trace printing for the error passed to Err().
logger.errorStackMarshaler must be set for this method to do something.
func Strings ¶ added in v1.3.2
Strings adds the field key with vals as a []string to the *Event context.
func Time ¶ added in v1.3.2
Time adds the field key with t formated as string using rz.TimeFieldFormat.
func Times ¶ added in v1.3.2
Times adds the field key with t formated as string using rz.TimeFieldFormat.
func Timestamp ¶ added in v0.13.5
Timestamp adds the current local time as UNIX timestamp to the *Event context with the logger.TimestampFieldName key.
func Uints16 ¶ added in v1.3.2
Uints16 adds the field key with i as a []uint16 to the *Event context.
func Uints32 ¶ added in v1.3.2
Uints32 adds the field key with i as a []uint32 to the *Event context.
type HookFunc ¶ added in v0.13.4
HookFunc is an adaptor to allow the use of an ordinary function as a LogHook.
type LevelHook ¶ added in v0.13.4
type LevelHook struct {
NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook LogHook
}
LevelHook applies a different hook for each level.
func NewLevelHook ¶ added in v0.13.4
func NewLevelHook() LevelHook
NewLevelHook returns a new LevelHook.
type LevelWriter ¶ added in v0.13.4
LevelWriter defines as interface a writer may implement in order to receive level information with payload.
func MultiLevelWriter ¶ added in v0.13.4
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 ¶ added in v0.13.8
LogFormatter can be used to log to another format than JSON
func FormatterCLI ¶ added in v1.1.0
func FormatterCLI() LogFormatter
FormatterCLI prettify output suitable for command-line interfaces.
func FormatterConsole ¶ added in v1.1.0
func FormatterConsole() LogFormatter
FormatterConsole prettify output for human cosumption
func FormatterLogfmt ¶ added in v1.1.0
func FormatterLogfmt() LogFormatter
FormatterLogfmt prettify output for human consumption, using the logfmt format.
type LogHook ¶ added in v0.13.4
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 ¶ added in v0.13.4
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 ¶ added in v0.13.4
ParseLevel converts a level string into a rz Level value. returns an error if the input string does not match known values.
type LogObjectMarshaler ¶ added in v0.13.4
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 ¶ added in v0.13.4
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 ¶ added in v0.13.4
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 ¶ added in v0.13.4
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 ¶ added in v0.13.4
func Nop() Logger
Nop returns a disabled logger for which all operation are no-op.
func (*Logger) Append ¶ added in v1.1.0
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) Fatal ¶
Fatal logs a new message with fatal level. The os.Exit(1) function is then called, which terminates the program immediately.
func (*Logger) Log ¶ added in v0.13.4
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 v1.3.2
LogWithLevel logs a new message with the given level.
func (*Logger) NewDict ¶ added in v1.3.2
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 ¶ added in v0.13.4
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 ¶ added in v0.13.4
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) 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
type LoggerOption ¶
type LoggerOption func(logger *Logger)
LoggerOption is used to configure a logger.
func CallerFieldName ¶ added in v0.13.4
func CallerFieldName(callerFieldName string) LoggerOption
CallerFieldName update logger's callerFieldName.
func CallerSkipFrameCount ¶ added in v0.13.4
func CallerSkipFrameCount(callerSkipFrameCount int) LoggerOption
CallerSkipFrameCount update logger's callerSkipFrameCount.
func ErrorFieldName ¶ added in v0.13.4
func ErrorFieldName(errorFieldName string) LoggerOption
ErrorFieldName update logger's errorFieldName.
func ErrorStackFieldName ¶ added in v0.13.4
func ErrorStackFieldName(errorStackFieldName string) LoggerOption
ErrorStackFieldName update logger's errorStackFieldName.
func Fields ¶ added in v1.3.2
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 ¶ added in v0.13.4
func Hooks(hooks ...LogHook) LoggerOption
Hooks replaces logger's hooks
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 ¶ added in v0.13.4
func Sampler(sampler LogSampler) LoggerOption
Sampler update logger's sampler.
func TimeFieldFormat ¶ added in v0.13.4
func TimeFieldFormat(timeFieldFormat string) LoggerOption
TimeFieldFormat update logger's timeFieldFormat.
func TimestampFieldName ¶
func TimestampFieldName(timestampFieldName string) LoggerOption
TimestampFieldName update logger's timestampFieldName.
func TimestampFunc ¶ added in v0.13.4
func TimestampFunc(timestampFunc func() time.Time) LoggerOption
TimestampFunc update logger's timestampFunc.
func Writer ¶ added in v0.13.4
func Writer(writer io.Writer) LoggerOption
Writer update logger's writer.
type SamplerBasic ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (s *SamplerBasic) Sample(lvl LogLevel) bool
Sample implements the Sampler interface.
type SamplerBurst ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (s *SamplerBurst) Sample(lvl LogLevel) bool
Sample implements the Sampler interface.
type SamplerLevel ¶ added in v1.1.0
type SamplerLevel struct { DebugSampler LogSampler InfoSampler LogSampler WarnSampler LogSampler ErrorSampler LogSampler }
SamplerLevel applies a different sampler for each level.
func (SamplerLevel) Sample ¶ added in v1.1.0
func (s SamplerLevel) Sample(lvl LogLevel) bool
Sample implements the Sampler interface.
type SamplerRandom ¶ added in v1.1.0
type SamplerRandom uint32
SamplerRandom use a PRNG to randomly sample an event out of N events, regardless of their level.
func (SamplerRandom) Sample ¶ added in v1.1.0
func (s SamplerRandom) Sample(lvl LogLevel) bool
Sample implements the Sampler interface.
Source Files ¶
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 |