log

package
v0.0.0-...-c19cbcf Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2020 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

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

A global Logger can be used for simple logging:

import "github.com/bloom42/gobox/log"

log.Info("hello world")

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

Fields can be added to log messages:

log.Info("hello world", log.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 := log.New()
log.Info("hello world",log.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.Clone(log.String("component", "foo"))
sublogger.Info("hello world", nil)

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

This example uses command-line flags to demonstrate various outputs depending on the chosen log level.

package main

import (
	"flag"
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	debug := flag.Bool("debug", false, "sets log level to debug")

	flag.Parse()

	// Default level for this example is info, unless debug flag is present

	if *debug {
		logger := log.GlobalLogger()
		defer func() {
			log.SetGlobalLogger(logger)
		}()
		log.SetGlobalLogger(log.Clone(log.SetLevel(log.DebugLevel)))
	}

	log.Info("This message appears when log level set to Debug or Info")

}
Output:

{"level":"info","timestamp":1199811905,"message":"This message appears when log level set to Debug or Info"}

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"

	// 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)
)

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 log 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 Append

func 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 `Config(Clone(fields...))` often is preferable.

func Debug

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

Debug starts a new message with debug level.

Example

Example of a log at a particular "level" (in this case, "debug")

package main

import (
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	log.Debug("hello world")

}
Output:

{"level":"debug","timestamp":1199811905,"message":"hello world"}

func Error

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

Error logs a message with error level.

Example

Example of a log at a particular "level" (in this case, "error")

package main

import (
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	log.Error("hello world")

}
Output:

{"level":"error","timestamp":1199811905,"message":"hello world"}

func Fatal

func 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.

Example

Example of a log at a particular "level" (in this case, "fatal")

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	err := errors.New("A repo man spends his life getting into tense situations")
	service := "myservice"

	log.Fatal(fmt.Sprintf("Cannot start %s", service), log.Err("error", err), log.String("service", service))

	// Outputs: {"level":"fatal","timestamp":1199811905,"error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"}
}
Output:

func Info

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

Info logs a new message with info level.

Example

Example of a log at a particular "level" (in this case, "info")

package main

import (
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	log.Info("hello world")

}
Output:

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

func Log

func 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.

Example

Example of a log with no particular "level"

package main

import (
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	log.Log("hello world")

}
Output:

{"timestamp":1199811905,"message":"hello world"}

func LogWithLevel

func LogWithLevel(level Level, message string, fields ...Field)

LogWithLevel logs a new message with the given level.

func Panic

func 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 SetGlobalLogger

func SetGlobalLogger(logger Logger)

SetGlobalLogger update the global logger

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 log guaranties to issue a single Write call per log event.

func Warn

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

Warn logs a new message with warn level.

Example

Example of a log at a particular "level" (in this case, "warn")

package main

import (
	"time"

	"github.com/bloom42/gobox/log"
)

// setup would normally be an init() function, however, there seems
// to be something awry with the testing framework when we set the
// global Logger from an init()
func setup() {

	log.SetGlobalLogger(log.New(log.SetTimeFieldFormat(""), log.SetTimestampFunc(func() time.Time {
		return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
	})))
}

func main() {
	setup()
	log.Warn("hello world")

}
Output:

{"level":"warning","timestamp":1199811905,"message":"hello world"}

Types

type ArrayMarshaler

type ArrayMarshaler interface {
	MarshalLogArray(*array)
}

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

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 NewDict

func NewDict(fields ...Field) *Event

NewDict create a new Dict with the logger's configuration

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

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 Base64

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

Base64 adds the field key with val as a base64 string to the *Event context. Allocate.

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 log.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 log.DurationFieldUnit. If log.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 log.DurationFieldUnit. If log.DurationFieldInteger is true, durations are rendered as integer instead of float.

func EmbedObject

func EmbedObject(obj ObjectMarshaler) Field

EmbedObject marshals an object that implement the ObjectMarshaler interface.

func Err

func Err(key string, value error) Field

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

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

func Errs

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

Errs 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 ObjectMarshaler) Field

Object marshals an object that implement the ObjectMarshaler 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 log.TimeFieldFormat.

func Times

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

Times adds the field key with t formated as string using log.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 UUID

func UUID(key string, value uuid.UUID) Field

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

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 Formatter

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

Formatter can be used to log to another format than JSON

func FormatterCLI

func FormatterCLI() Formatter

FormatterCLI prettify output suitable for command-line interfaces.

func FormatterConsole

func FormatterConsole() Formatter

FormatterConsole prettify output for human cosumption

func FormatterLogfmt

func FormatterLogfmt() Formatter

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

type Hook

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

Hook defines an interface to a log hook.

type HookFunc

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

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

func (HookFunc) Run

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

Run implements the Hook interface.

type Level

type Level uint8

Level defines log levels.

const (
	// DebugLevel defines debug log level.
	DebugLevel Level = 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) (Level, error)

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

func (Level) String

func (l Level) String() string

type LevelHook

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

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 Level, message string)

Run implements the Hook interface.

type LevelWriter

type LevelWriter interface {
	io.Writer
	WriteLevel(level Level, 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 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 Clone

func Clone(options ...LoggerOption) Logger

Clone duplicates the global logger and update it's configuration.

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 "log.FromCtx": "error".

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

ctx := r.Context()
l := log.FromCtx(ctx)
l.Clone(...)

func GlobalLogger

func GlobalLogger() Logger

GlobalLogger returns the global logger

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
package main

import (
	"github.com/bloom42/gobox/log"
)

func main() {
	log := log.New(log.SetFields(log.Timestamp(false)))

	log.Info("hello world")
}
Output:

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

func NewNop

func NewNop() Logger

NewNop 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 `Clone(Fields(fields...))` often is preferable.

func (Logger) Clone

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

Clone create a new clone of the logger and apply all the options to the new logger

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

func (l *Logger) GetLevel() Level

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

func (l *Logger) LogWithLevel(level Level, 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) 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 := log.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 Hook) LoggerOption

AddHook appends hook to logger's hook

func SetCallerFieldName

func SetCallerFieldName(callerFieldName string) LoggerOption

SetCallerFieldName update logger's callerFieldName.

func SetCallerSkipFrameCount

func SetCallerSkipFrameCount(callerSkipFrameCount int) LoggerOption

SetCallerSkipFrameCount update logger's callerSkipFrameCount.

func SetErrorStackFieldName

func SetErrorStackFieldName(errorStackFieldName string) LoggerOption

SetErrorStackFieldName update logger's errorStackFieldName.

func SetFields

func SetFields(fields ...Field) LoggerOption

SetFields update logger's context fields

func SetFormatter

func SetFormatter(formatter Formatter) LoggerOption

SetFormatter update logger's formatter.

func SetHooks

func SetHooks(hooks ...Hook) LoggerOption

SetHooks replaces logger's hooks

func SetLevel

func SetLevel(lvl Level) LoggerOption

SetLevel update logger's level.

func SetLevelFieldName

func SetLevelFieldName(levelFieldName string) LoggerOption

SetLevelFieldName update logger's levelFieldName.

func SetMessageFieldName

func SetMessageFieldName(messageFieldName string) LoggerOption

SetMessageFieldName update logger's messageFieldName.

func SetSampler

func SetSampler(sampler Sampler) LoggerOption

SetSampler update logger's sampler.

func SetTimeFieldFormat

func SetTimeFieldFormat(timeFieldFormat string) LoggerOption

SetTimeFieldFormat update logger's timeFieldFormat.

func SetTimestampFieldName

func SetTimestampFieldName(timestampFieldName string) LoggerOption

SetTimestampFieldName update logger's timestampFieldName.

func SetTimestampFunc

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

SetTimestampFunc update logger's timestampFunc.

func SetWriter

func SetWriter(writer io.Writer) LoggerOption

SetWriter update logger's writer.

type ObjectMarshaler

type ObjectMarshaler interface {
	MarshalLogObject(*Event)
}

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

type Sampler

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

Sampler defines an interface to a log sampler.

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 Level) 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 Sampler
	// 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 Level) bool

Sample implements the Sampler interface.

type SamplerLevel

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

SamplerLevel applies a different sampler for each level.

func (SamplerLevel) Sample

func (s SamplerLevel) Sample(lvl Level) 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 Level) bool

Sample implements the Sampler interface.

Directories

Path Synopsis
internal
Package loghttp provides an helper middleware to log HTTP requests See https://github.com/bloom42/gobox/log/tree/master/examples/http for a working example
Package loghttp provides an helper middleware to log HTTP requests See https://github.com/bloom42/gobox/log/tree/master/examples/http for a working example
Package pkgerrors is on the way of deprecation due to go2 error value https://github.com/pkg/errors
Package pkgerrors is on the way of deprecation due to go2 error value https://github.com/pkg/errors

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳