zero

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 30 Imported by: 0

README

zero godoc test Coverage Status Release License

zero is a fast, structured logger for Go focused on JSON and CBOR output.

It keeps the fluent, low-allocation style of the original zero API, but the module was renamed to the zero package and repository path. The supported import path is now:

  • github.com/malivvan/zero
  • github.com/malivvan/zero/log

If you are migrating from the older zero package, the main changes are the module path and the package name: use zero.New(...) instead of a zero import, and use github.com/malivvan/zero instead of github.com/rs/zero.

Features

  • Low-allocation JSON and CBOR logging
  • Structured fields with a fluent builder API
  • Levels, sampling, hooks, and contextual loggers
  • context.Context integration
  • Pretty terminal output for development
  • log/slog bridge
  • Support for file output and custom encoders

Installation

go get github.com/malivvan/zero/log

Quick start

package main

import (
    "github.com/malivvan/zero/log"
)

func main() {
    log.Info().
        Str("service", "api").
        Str("env", "prod").
        Msg("hello world")
}

Output:

{"L":"info","service":"api","env":"prod","T":1712345678,"M":"hello world"}

Field names and the time format are compact by default to keep message size small: the timestamp is a UNIX integer stored under T, the level under L and the message under M. They can be overridden at any time:

zero.TimestampFieldName = "time"
zero.LevelFieldName = "level"
zero.MessageFieldName = "message"
zero.TimeFieldFormat = time.RFC3339

Global logger

The global logger package is github.com/malivvan/zero/log.

package main

import (
    "github.com/malivvan/zero/log"
)

func main() {
    log.Info().Msg("startup complete")
}

The global logger honors the following environment variables:

Variable Default Description
NOCOLOR false Disable pretty terminal colors
LOG_LEVEL info Global log level
LOG_FORMAT json json or cbor
LOG_FILE unset Enables rolling file logging
LOG_FILE_SIZE 100 Max file size in MB
LOG_FILE_AGE 7 Max age in days
LOG_FILE_FORMAT JSON JSON or CBOR
LOG_FILE_BACKUP 10 Max backups
LOG_FILE_COMPRESS true Enable compression
LOG_FILE_LEVEL LOG_LEVEL Per-file log level

Structured logging

Fields are added with strongly typed methods:

log.Debug().
    Str("scale", "833 cents").
    Float64("interval", 833.09).
    Msg("Fibonacci is everywhere")
{"L":"debug","scale":"833 cents","interval":833.09,"M":"Fibonacci is everywhere"}

Common field helpers include:

  • Str, Bool, Int, Int64, Uint64
  • Float32, Float64
  • Time, Timestamp, Dur
  • Err, Dict, RawJSON, Hex
  • Interface, IPAddr, IPPrefix, MACAddr

Levels and filtering

zero supports the following levels, from highest to lowest:

  • PanicLevel
  • FatalLevel
  • ErrorLevel
  • WarnLevel
  • InfoLevel
  • DebugLevel
  • TraceLevel
zero.SetGlobalLevel(zero.InfoLevel)

log.Debug().Msg("hidden")
log.Info().Msg("shown")

You can also check whether a level is enabled before doing expensive work:

if e := log.Debug(); e.Enabled() {
    value := expensiveComputation()
    e.Str("value", value).Msg("debug detail")
}

Context and sub-loggers

logger := zero.New(os.Stdout)
ctx := logger.WithContext(context.Background())

sub := log.With().Str("component", "http").Logger()
sub.Info().Msg("request processed")

loggerFromCtx := zero.Ctx(ctx)
loggerFromCtx.Info().Msg("context logger")

Error logging

err := errors.New("database unavailable")
log.Error().Err(err).Msg("request failed")

Output:

{"L":"error","E":"database unavailable","M":"request failed"}

The default error field name is E, and it can be overridden by setting zero.ErrorFieldName.

Hooks and sampling

type SeverityHook struct{}

func (h SeverityHook) Run(e *zero.Event, level zero.Level, msg string) {
    if level != zero.NoLevel {
        e.Str("severity", level.String())
    }
}

hooked := log.Hook(SeverityHook{})
hooked.Warn().Msg("attention")

Sampling is also supported:

sampled := log.Sample(&zero.BasicSampler{N: 10})
sampled.Info().Msg("logged every 10 messages")

Pretty output

log.Logger = log.Output(zero.TerminalWriter{Out: os.Stderr})
log.Info().Str("foo", "bar").Msg("Hello world")

This produces a human-friendly line for interactive terminals while preserving structured fields in the background logger.

JSON and CBOR

By default, zero writes JSON. You can switch to CBOR per logger:

logger := zero.New(os.Stdout).Encoder(zero.NewCBOREncoder())
logger.Info().Msg("binary output")

The terminal and console helpers transparently decode CBOR back to JSON when needed.

log/slog integration

package main

import (
    "log/slog"

    "github.com/malivvan/zero"
    "github.com/malivvan/zero/log"
)

func main() {
    handler := zero.NewSlogHandler(log.Logger)
    logger := slog.New(handler)
    logger.Info("user logged in", "user", "alice", "role", "admin")
}

Migration from zero

The project was renamed from the older zero package to zero, including the Go module path.

Old:

import "github.com/rs/zero"

New:

import "github.com/malivvan/zero"

The fluent API remains familiar, but the package and the module path are now zero rather than zero.

Caveats

Field duplication

zero does not de-duplicate fields. Reusing the same key adds multiple keys to the final JSON payload:

logger := zero.New(os.Stderr).With().Timestamp().Logger()
logger.Info().Timestamp().Msg("dup")

This may produce output like:

{"L":"info","T":1712345678,"T":1712345678,"M":"dup"}
Concurrency safety

When mutating a logger context, prefer creating a child logger with With() instead of modifying a shared logger concurrently.

Benchmarks

zero is optimized for low allocation and high throughput. See the project benchmarks and the public logbench site for current numbers.

License

This project is licensed under the MIT License. See LICENSE for details.

Documentation

Overview

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

A global Logger can be use for simple logging:

import "github.com/malivvan/zero/log"

log.Info().Msg("hello world")
// Output: {"L":"info","T":1494567715,"M":"hello world"}

NOTE: To import the global logger, import the "log" subpackage "github.com/malivvan/zero/log".

Fields can be added to log messages:

log.Info().Str("foo", "bar").Msg("hello world")
// Output: {"L":"info","foo":"bar","T":1494567715,"M":"hello world"}

Create logger instance to manage different outputs:

logger := zero.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
       Str("foo", "bar").
       Msg("hello world")
// Output: {"L":"info","foo":"bar","T":1494567715,"M":"hello world"}

Sub-loggers let you chain loggers with additional context:

sublogger := log.With().Str("component", "foo").Logger()
sublogger.Info().Msg("hello world")
// Output: {"L":"info","component":"foo","T":1494567715,"M":"hello world"}

Level logging

zero.SetGlobalLevel(zero.InfoLevel)

log.Debug().Msg("filtered out message")
log.Info().Msg("routed message")

if e := log.Debug(); e.Enabled() {
    // Compute log output only if enabled.
    value := compute()
    e.Str("foo": value).Msg("some debug message")
}
// Output: {"L":"info","T":1494567715,"M":"routed message"}

Customize automatic field names:

log.TimestampFieldName = "t"
log.LevelFieldName = "p"
log.MessageFieldName = "m"

log.Info().Msg("hello world")
// Output: {"t":1494567715,"p":"info","m":"hello world"}

Log with no level and message:

log.Log().Str("foo","bar").Msg("")
// Output: {"T":1494567715,"foo":"bar"}

Add contextual fields to global Logger:

log.Logger = log.With().Str("foo", "bar").Logger()

Sample logs:

sampled := log.Sample(&zero.BasicSampler{N: 10})
sampled.Info().Msg("will be logged every 10 messages")

Log with contextual hooks:

// Create the hook:
type SeverityHook struct{}

func (h SeverityHook) Run(e *zero.Event, level zero.Level, msg string) {
     if level != zero.NoLevel {
         e.Str("severity", level.String())
     }
}

// And use it:
var h SeverityHook
log := zero.New(os.Stdout).Hook(h)
log.Warn().Msg("")
// Output: {"L":"warn","severity":"warn"}

Caveats

Field duplication:

There is no fields deduplication out-of-the-box. Using the same key multiple times creates new key in final JSON each time.

logger := zero.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
       Timestamp().
       Msg("dup")
// Output: {"L":"info","T":1494567715,"T":1494567715,"M":"dup"}

In this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt.

Concurrency safety:

Be careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger:

func handler(w http.ResponseWriter, r *http.Request) {
    // Create a child logger for concurrency safety
    logger := log.Logger.With().Logger()

    // Add context fields, for example User-Agent from HTTP headers
    logger.UpdateContext(func(c zero.Context) zero.Context {
        ...
    })
}

Index

Constants

View Source
const (
	// TimeFormatUnix defines a time format that makes time fields to be
	// serialized as Unix timestamp integers.
	TimeFormatUnix = ""

	// TimeFormatUnixMs defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in milliseconds.
	TimeFormatUnixMs = "UNIXMS"

	// TimeFormatUnixMicro defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in microseconds.
	TimeFormatUnixMicro = "UNIXMICRO"

	// TimeFormatUnixNano defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in nanoseconds.
	TimeFormatUnixNano = "UNIXNANO"

	// DurationFormatFloat defines a format for Duration fields that makes duration fields to be
	// serialized as floating point numbers.
	DurationFormatFloat = "float"
	// DurationFormatInt defines a format for Duration fields that makes duration fields to be
	// serialized as integers.
	DurationFormatInt = "int"
	// DurationFormatString defines a format for Duration fields that makes duration fields to be
	// serialized as string.
	DurationFormatString = "string"
)

Variables

View Source
var (
	// TimestampFieldName is the field name used for the timestamp field.
	TimestampFieldName = "T"

	// LevelFieldName is the field name used for the level field.
	LevelFieldName = "L"

	// LevelTraceValue is the value used for the trace level field.
	LevelTraceValue = "trace"
	// LevelDebugValue is the value used for the debug level field.
	LevelDebugValue = "debug"
	// LevelInfoValue is the value used for the info level field.
	LevelInfoValue = "info"
	// LevelWarnValue is the value used for the warn level field.
	LevelWarnValue = "warn"
	// LevelErrorValue is the value used for the error level field.
	LevelErrorValue = "error"
	// LevelFatalValue is the value used for the fatal level field.
	LevelFatalValue = "fatal"
	// LevelPanicValue is the value used for the panic level field.
	LevelPanicValue = "panic"

	// LevelFieldMarshalFunc allows customization of global level field marshaling.
	LevelFieldMarshalFunc = func(l Level) string {
		return l.String()
	}

	// MessageFieldName is the field name used for the message field.
	MessageFieldName = "M"

	// ErrorFieldName is the field name used for error fields.
	ErrorFieldName = "E"

	// CallerFieldName is the field name used for caller field.
	CallerFieldName = "C"

	// CallerSkipFrameCount is the number of stack frames to skip to find the caller.
	CallerSkipFrameCount = 2

	// CallerMarshalFunc allows customization of global caller marshaling
	CallerMarshalFunc = func(pc uintptr, file string, line int) string {
		return file + ":" + strconv.Itoa(line)
	}

	// ErrorStackFieldName is the field name used for error stacks.
	ErrorStackFieldName = "S"

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

	// InterfaceMarshalFunc allows customization of interface marshaling.
	// Default: "encoding/json.Marshal" with disabled HTML escaping
	InterfaceMarshalFunc = func(v interface{}) ([]byte, error) {
		var buf bytes.Buffer
		encoder := json.NewEncoder(&buf)
		encoder.SetEscapeHTML(false)
		err := encoder.Encode(v)
		if err != nil {
			return nil, err
		}
		b := buf.Bytes()
		if len(b) > 0 {

			return b[:len(b)-1], nil
		}
		return b, nil
	}

	// TimeFieldFormat defines the time format of the Time field type. If set to
	// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX
	// timestamp as integer.
	TimeFieldFormat = TimeFormatUnix

	// TimestampFunc defines the function called to generate a timestamp.
	TimestampFunc = time.Now

	// DurationFieldFormat defines the format of the Duration field type.
	DurationFieldFormat = DurationFormatFloat

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

	// DurationFieldInteger renders Dur fields as integer instead of float if
	// set to true.
	// Deprecated: use DurationFieldFormat with DurationFormatInt instead.
	DurationFieldInteger = false

	// ErrorHandler is called whenever zero 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)

	// FatalExitFunc is called by log.Fatal() instead of os.Exit(1). If not set,
	// os.Exit(1) is called.
	FatalExitFunc func()

	// DefaultContextLogger is returned from Ctx() if there is no logger associated
	// with the context.
	DefaultContextLogger *Logger

	// LevelColors are used by TerminalWriter's terminalDefaultFormatLevel to color
	// log levels.
	LevelColors = map[Level]int{
		TraceLevel: colorBlue,
		DebugLevel: 0,
		InfoLevel:  colorGreen,
		WarnLevel:  colorYellow,
		ErrorLevel: colorRed,
		FatalLevel: colorRed,
		PanicLevel: colorRed,
	}

	// FormattedLevels are used by TerminalWriter's terminalDefaultFormatLevel
	// for a short level name.
	FormattedLevels = map[Level]string{
		TraceLevel: "TRC",
		DebugLevel: "DBG",
		InfoLevel:  "INF",
		WarnLevel:  "WRN",
		ErrorLevel: "ERR",
		FatalLevel: "FTL",
		PanicLevel: "PNC",
	}

	// TriggerLevelWriterBufferReuseLimit is a limit in bytes that a buffer is dropped
	// from the TriggerLevelWriter buffer pool if the buffer grows above the limit.
	TriggerLevelWriterBufferReuseLimit = 64 * 1024

	// FloatingPointPrecision, if set to a value other than -1, controls the number
	// of digits when formatting float numbers in JSON. See strconv.FormatFloat for
	// more details.
	FloatingPointPrecision = -1
)
View Source
var (
	// Often samples log every ~ 10 events.
	Often = RandomSampler(10)
	// Sometimes samples log every ~ 100 events.
	Sometimes = RandomSampler(100)
	// Rarely samples log every ~ 1000 events.
	Rarely = RandomSampler(1000)
)
View Source
var (
	StackSourceFileName     = "source"
	StackSourceLineName     = "line"
	StackSourceFunctionName = "func"
)
View Source
var ErrConsoleUnavailable = errors.New("zero: JavaScript console unavailable")

ErrConsoleUnavailable is returned by ConsoleWriter on platforms without a JavaScript console (i.e. not js/wasm) or when the console global is missing.

View Source
var SendFunc func(string, journal.Priority, map[string]string) error

SendFunc is the function used to send logs to journald. It can be replaced in tests for mocking. If nil, journal.Send is used directly. This variable should only be modified in tests and must not be changed while the writer is in use. Tests that modify this variable should not use t.Parallel().

Functions

func AsStringers

func AsStringers[T fmt.Stringer](objs []T) []fmt.Stringer

AsStringers converts a slice of T (implementing fmt.Stringer) into a slice of fmt.Stringer.

func ConsoleAvailable

func ConsoleAvailable() bool

ConsoleAvailable reports whether the JavaScript console API can be used (true only on js/wasm when a console global exists).

func DisableSampling

func DisableSampling(v bool)

DisableSampling will disable sampling in all Loggers if true.

func MarshalStack

func MarshalStack(err error) interface{}

MarshalStack returns a pkg/errors stack trace as a field value, ready to be assigned to ErrorStackMarshaler:

zero.ErrorStackMarshaler = zero.MarshalStack

func NewJournalDWriter

func NewJournalDWriter() io.Writer

NewJournalDWriter returns a zero log destination to be used as parameter to New() calls. Writing logs to this writer will send the log messages to journalD running in this system.

func SetGlobalLevel

func SetGlobalLevel(l Level)

SetGlobalLevel sets the global override for log level. If this values is raised, all Loggers will use at least this value.

To globally disable logs, set GlobalLevel to Disabled.

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 used to wrap the call to writer's Write method if it is not thread safe. Note that you do not need this wrapper for os.File Write operations on POSIX and Windows systems as they are already thread-safe.

func TerminalTestWriter

func TerminalTestWriter(t TestingLog) func(w *TerminalWriter)

TerminalTestWriter creates an option that correctly sets the file frame depth for testing.TB log.

Types

type Array

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

Array is used to prepopulate an array of items which can be re-used to add to log messages.

func Arr

func Arr() *Array

Arr creates an array to be added to an Event or Context. WARNING: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateArray or Context.CreateArray instead.

func (*Array) Bool

func (a *Array) Bool(b bool) *Array

Bool appends the val as a bool to the array.

func (*Array) Bytes

func (a *Array) Bytes(val []byte) *Array

Bytes appends the val as a string to the array.

func (*Array) Dict

func (a *Array) Dict(dict *Event) *Array

Dict adds the dict Event to the array

func (*Array) Dur

func (a *Array) Dur(d time.Duration) *Array

Dur appends d to the array.

func (*Array) Err

func (a *Array) Err(err error) *Array

Err serializes and appends the err to the array.

func (*Array) Errs

func (a *Array) Errs(errs []error) *Array

Errs serializes and appends errors to the array.

func (*Array) Float32

func (a *Array) Float32(f float32) *Array

Float32 appends f as a float32 to the array.

func (*Array) Float64

func (a *Array) Float64(f float64) *Array

Float64 appends f as a float64 to the array.

func (*Array) Hex

func (a *Array) Hex(val []byte) *Array

Hex appends the val as a hex string to the array.

func (*Array) IPAddr

func (a *Array) IPAddr(ip net.IP) *Array

IPAddr adds a net.IP IPv4 or IPv6 address to the array

func (*Array) IPPrefix

func (a *Array) IPPrefix(pfx net.IPNet) *Array

IPPrefix adds a net.IPNet IPv4 or IPv6 Prefix (IP + mask) to the array

func (*Array) Int

func (a *Array) Int(i int) *Array

Int appends i as a int to the array.

func (*Array) Int8

func (a *Array) Int8(i int8) *Array

Int8 appends i as a int8 to the array.

func (*Array) Int16

func (a *Array) Int16(i int16) *Array

Int16 appends i as a int16 to the array.

func (*Array) Int32

func (a *Array) Int32(i int32) *Array

Int32 appends i as a int32 to the array.

func (*Array) Int64

func (a *Array) Int64(i int64) *Array

Int64 appends i as a int64 to the array.

func (*Array) Interface

func (a *Array) Interface(i interface{}) *Array

Interface appends i marshaled using reflection.

func (*Array) MACAddr

func (a *Array) MACAddr(ha net.HardwareAddr) *Array

MACAddr adds a net.HardwareAddr MAC (Ethernet) address to the array

func (*Array) MarshalZeroArray

func (*Array) MarshalZeroArray(*Array)

MarshalZeroArray method here is no-op - since data is already in the needed format.

func (*Array) Object

func (a *Array) Object(obj LogObjectMarshaler) *Array

Object marshals an object that implement the LogObjectMarshaler interface and appends it to the array.

func (*Array) RawJSON

func (a *Array) RawJSON(val []byte) *Array

RawJSON adds already encoded JSON to the array.

func (*Array) Str

func (a *Array) Str(val string) *Array

Str appends the val as a string to the array.

func (*Array) Time

func (a *Array) Time(t time.Time) *Array

Time appends t formatted as string using zero.TimeFieldFormat.

func (*Array) Type

func (a *Array) Type(val interface{}) *Array

Type adds the val's type using reflection to the array.

func (*Array) Uint

func (a *Array) Uint(i uint) *Array

Uint appends i as a uint to the array.

func (*Array) Uint8

func (a *Array) Uint8(i uint8) *Array

Uint8 appends i as a uint8 to the array.

func (*Array) Uint16

func (a *Array) Uint16(i uint16) *Array

Uint16 appends i as a uint16 to the array.

func (*Array) Uint32

func (a *Array) Uint32(i uint32) *Array

Uint32 appends i as a uint32 to the array.

func (*Array) Uint64

func (a *Array) Uint64(i uint64) *Array

Uint64 appends i as a uint64 to the array.

type AsyncAlerter

type AsyncAlerter func(missed int)

AsyncAlerter is called when the diode drops messages because the underlying writer cannot keep up.

type AsyncWriter

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

AsyncWriter is an io.Writer wrapper that uses a diode to make Write lock-free, non-blocking and thread safe.

func NewAsyncWriter

func NewAsyncWriter(w io.Writer, size int, pollInterval time.Duration, f AsyncAlerter) AsyncWriter

NewAsyncWriter creates a writer wrapping w with a many-to-one diode in order to never block log producers and drop events if the writer can't keep up with the flow of data.

Use an AsyncWriter when

wr := zero.NewAsyncWriter(w, 1000, 0, func(missed int) {
    log.Printf("Dropped %d messages", missed)
})
log := zero.New(wr)

If pollInterval is greater than 0, a poller is used otherwise a waiter is used.

A size of zero or less is treated as 1.

See code.cloudfoundry.org/go-diodes for more info on diode.

func (AsyncWriter) Close

func (dw AsyncWriter) Close() error

Close releases the diode poller and call Close on the wrapped writer if io.Closer is implemented.

func (AsyncWriter) Write

func (dw AsyncWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

type BasicSampler

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

BasicSampler is a sampler that will send every Nth event, regardless of their level.

func (*BasicSampler) Sample

func (s *BasicSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

type BurstSampler

type BurstSampler 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
}

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

func (*BurstSampler) Sample

func (s *BurstSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

type ConsoleWriter

type ConsoleWriter struct{}

ConsoleWriter writes log events to the JavaScript console using console.debug, console.info, console.warn and console.error according to the event level. It is meant for js/wasm environments (GOOS=js GOARCH=wasm), where stdout/stderr are not available: the output goes exclusively through the console API.

The writer implements both io.Writer and LevelWriter: when used with New, each event is routed to the console method matching its level. When used as a plain io.Writer, the level is extracted from the JSON (or CBOR) payload; lines that cannot be parsed are logged with console.log.

On non-js platforms every write returns ErrConsoleUnavailable.

func NewConsoleWriter

func NewConsoleWriter() *ConsoleWriter

NewConsoleWriter creates a writer that emits log events to the JavaScript console.

func (ConsoleWriter) Close

func (w ConsoleWriter) Close() error

Close implements io.Closer. There is nothing to close on the console.

func (ConsoleWriter) Write

func (w ConsoleWriter) Write(p []byte) (int, error)

Write implements io.Writer.

func (ConsoleWriter) WriteLevel

func (w ConsoleWriter) WriteLevel(l Level, p []byte) (int, error)

WriteLevel implements LevelWriter.

type Context

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

Context configures a new sub-logger with contextual fields.

func (Context) AnErr

func (c Context) AnErr(key string, err error) Context

AnErr adds the field key with serialized err to the logger context. If err is nil, no field is added.

func (Context) Any

func (c Context) Any(key string, i interface{}) Context

Any is a wrapper around Context.Interface.

func (Context) Array

func (c Context) Array(key string, arr LogArrayMarshaler) Context

Array adds the field key with an array to the event context. Use c.CreateArray() to create the array or pass a type that implement the LogArrayMarshaler interface.

func (Context) Bool

func (c Context) Bool(key string, b bool) Context

Bool adds the field key with val as a bool to the logger context.

func (Context) Bools

func (c Context) Bools(key string, b []bool) Context

Bools adds the field key with val as a []bool to the logger context.

func (Context) Bytes

func (c Context) Bytes(key string, val []byte) Context

Bytes adds the field key with val as a []byte to the logger context.

func (Context) Caller

func (c Context) Caller() Context

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

func (Context) CallerWithSkipFrameCount

func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context

CallerWithSkipFrameCount adds the file:line of the caller with the zero.CallerFieldName key. The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. If set to -1 the global CallerSkipFrameCount will be used.

func (Context) CreateArray

func (c Context) CreateArray() *Array

CreateArray creates an Array to be used with the Context.Array method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the Context.Array method.

func (Context) CreateDict

func (c Context) CreateDict() *Event

CreateDict creates an Event to be used with the Context.Dict method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the Context.Dict method.

func (Context) Ctx

func (c Context) Ctx(ctx context.Context) Context

Ctx adds the context.Context to the logger context. The context.Context is not rendered in the error message, but is made available for hooks to use. A typical use case is to extract tracing information from the context.Context.

func (Context) Dict

func (c Context) Dict(key string, dict *Event) Context

Dict adds the field key with the dict to the logger context.

func (Context) Dur

func (c Context) Dur(key string, d time.Duration) Context

Dur adds the field key with d divided by unit and stored as a float.

func (Context) Durs

func (c Context) Durs(key string, d []time.Duration) Context

Durs adds the field key with d divided by unit and stored as a float.

func (Context) EmbedObject

func (c Context) EmbedObject(obj LogObjectMarshaler) Context

EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.

func (Context) Err

func (c Context) Err(err error) Context

Err adds the field "error" with serialized err to the logger context.

func (Context) Errs

func (c Context) Errs(key string, errs []error) Context

Errs adds the field key with errs as an array of serialized errors to the logger context.

func (Context) Fields

func (c Context) Fields(fields interface{}) Context

Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.

func (Context) Float32

func (c Context) Float32(key string, f float32) Context

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

func (Context) Float64

func (c Context) Float64(key string, f float64) Context

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

func (Context) Floats32

func (c Context) Floats32(key string, f []float32) Context

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

func (Context) Floats64

func (c Context) Floats64(key string, f []float64) Context

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

func (Context) Hex

func (c Context) Hex(key string, val []byte) Context

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

func (Context) IPAddr

func (c Context) IPAddr(key string, ip net.IP) Context

IPAddr adds the field key with ip as a net.IP IPv4 or IPv6 Address to the context

func (Context) IPAddrs

func (c Context) IPAddrs(key string, ip []net.IP) Context

IPAddrs adds the field key with ip as a []net.IP array of IPv4 or IPv6 Address to the context

func (Context) IPPrefix

func (c Context) IPPrefix(key string, pfx net.IPNet) Context

IPPrefix adds the field key with pfx as a []net.IPNet IPv4 or IPv6 Prefix (address and mask) to the context

func (Context) IPPrefixes

func (c Context) IPPrefixes(key string, pfx []net.IPNet) Context

IPPrefix adds the field key with pfx as a []net.IPNet array of IPv4 or IPv6 Prefix (address and mask) to the context

func (Context) Int

func (c Context) Int(key string, i int) Context

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

func (Context) Int8

func (c Context) Int8(key string, i int8) Context

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

func (Context) Int16

func (c Context) Int16(key string, i int16) Context

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

func (Context) Int32

func (c Context) Int32(key string, i int32) Context

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

func (Context) Int64

func (c Context) Int64(key string, i int64) Context

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

func (Context) Interface

func (c Context) Interface(key string, i interface{}) Context

Interface adds the field key with obj marshaled using reflection.

func (Context) Ints

func (c Context) Ints(key string, i []int) Context

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

func (Context) Ints8

func (c Context) Ints8(key string, i []int8) Context

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

func (Context) Ints16

func (c Context) Ints16(key string, i []int16) Context

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

func (Context) Ints32

func (c Context) Ints32(key string, i []int32) Context

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

func (Context) Ints64

func (c Context) Ints64(key string, i []int64) Context

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

func (Context) Logger

func (c Context) Logger() Logger

Logger returns the logger with the context previously set.

func (Context) MACAddr

func (c Context) MACAddr(key string, ha net.HardwareAddr) Context

MACAddr adds the field key with ha as a net.HardwareAddr MAC address to the context

func (Context) Object

func (c Context) Object(key string, obj LogObjectMarshaler) Context

Object marshals an object that implement the LogObjectMarshaler interface.

func (Context) Objects

func (c Context) Objects(key string, objs []LogObjectMarshaler) Context

Objects adds the field key with objs to the logger context as an array of objects that implement the LogObjectMarshaler interface.

This is the array version that accepts a slice of LogObjectMarshaler objects.

func (Context) ObjectsV

func (c Context) ObjectsV(key string, objs ...LogObjectMarshaler) Context

ObjectsV adds the field key with objs to the logger context as an array of objects that implement the LogObjectMarshaler interface.

This is a variadic version that accepts a list of individual LogObjectMarshaler objects.

func (Context) RawJSON

func (c Context) RawJSON(key string, b []byte) Context

RawJSON adds already encoded JSON to context.

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

func (Context) Reset

func (c Context) Reset() Context

Reset removes all the context fields.

func (Context) Stack

func (c Context) Stack() Context

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

func (Context) Str

func (c Context) Str(key, val string) Context

Str adds the field key with val as a string to the logger context.

func (Context) Stringer

func (c Context) Stringer(key string, val fmt.Stringer) Context

Stringer adds the field key with val.String() (or null if val is nil) to the logger context.

func (Context) Stringers

func (c Context) Stringers(key string, vals []fmt.Stringer) Context

Stringers adds the field key with vals to the logger context where each individual val is added by calling val.String().

This is the array version that accepts a slice of fmt.Stringer values.

func (Context) StringersV

func (c Context) StringersV(key string, vals ...fmt.Stringer) Context

StringersV adds the field key with vals to the logger context where each individual val is added by calling val.String().

This is a variadic version that accepts a list of individual fmt.Stringer values.

func (Context) Strs

func (c Context) Strs(key string, vals []string) Context

Strs adds the field key with val as a string to the logger context.

This is the array version that accepts a slice of string values.

func (Context) StrsV

func (c Context) StrsV(key string, vals ...string) Context

StrsV adds the field key with vals as a []string to the logger context.

This is a variadic version that accepts a list of individual strings.

func (Context) Time

func (c Context) Time(key string, t time.Time) Context

Time adds the field key with t formatted as string using zero.TimeFieldFormat.

func (Context) Times

func (c Context) Times(key string, t []time.Time) Context

Times adds the field key with t formatted as string using zero.TimeFieldFormat.

func (Context) Timestamp

func (c Context) Timestamp() Context

Timestamp adds the current local time to the logger context with the TimestampFieldName key, formatted using zero.TimeFieldFormat. To customize the key name, change zero.TimestampFieldName. To customize the time format, change zero.TimeFieldFormat.

NOTE: It won't dedupe the "time" key if the *Context has one already.

func (Context) Type

func (c Context) Type(key string, val interface{}) Context

Type adds the field key with val's type using reflection.

func (Context) Uint

func (c Context) Uint(key string, i uint) Context

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

func (Context) Uint8

func (c Context) Uint8(key string, i uint8) Context

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

func (Context) Uint16

func (c Context) Uint16(key string, i uint16) Context

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

func (Context) Uint32

func (c Context) Uint32(key string, i uint32) Context

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

func (Context) Uint64

func (c Context) Uint64(key string, i uint64) Context

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

func (Context) Uints

func (c Context) Uints(key string, i []uint) Context

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

func (Context) Uints8

func (c Context) Uints8(key string, i []uint8) Context

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

func (Context) Uints16

func (c Context) Uints16(key string, i []uint16) Context

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

func (Context) Uints32

func (c Context) Uints32(key string, i []uint32) Context

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

func (Context) Uints64

func (c Context) Uints64(key string, i []uint64) Context

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

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, format string, useInt bool, precision int) []byte
	AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, format string, useInt bool, precision int) []byte
	AppendEmbeddedCBOR(dst []byte, c []byte) []byte
	AppendEmbeddedJSON(dst []byte, j []byte) []byte
	AppendEndMarker(dst []byte) []byte
	AppendFloat32(dst []byte, val float32, precision int) []byte
	AppendFloat64(dst []byte, val float64, precision int) []byte
	AppendFloats32(dst []byte, vals []float32, precision int) []byte
	AppendFloats64(dst []byte, vals []float64, precision int) []byte
	AppendHex(dst, s []byte) []byte
	AppendIPAddr(dst []byte, ip net.IP) []byte
	AppendIPAddrs(dst []byte, vals []net.IP) []byte
	AppendIPPrefix(dst []byte, pfx net.IPNet) []byte
	AppendIPPrefixes(dst []byte, vals []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
	AppendStringer(dst []byte, val fmt.Stringer) []byte
	AppendStringers(dst []byte, vals []fmt.Stringer) []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
	AppendType(dst []byte, i interface{}) []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 the interface implemented by the log message encoders (JSON, CBOR, ...). The logger output format is chosen at runtime by selecting the encoder passed to New or Logger.Encoder.

func NewCBOREncoder

func NewCBOREncoder() Encoder

NewCBOREncoder returns the CBOR (binary) log message encoder. Select it at runtime with Logger.Encoder, e.g.:

logger := zero.New(w).Encoder(zero.NewCBOREncoder())

func NewJSONEncoder

func NewJSONEncoder() Encoder

NewJSONEncoder returns the JSON log message encoder. It is the default encoder used by New and Logger.Encoder.

type Event

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

Event represents a log event. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.

func Dict

func Dict() *Event

Dict creates an Event to be used with the *Event.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. NOTE: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateDict instead.

func (*Event) AnErr

func (e *Event) AnErr(key string, err error) *Event

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

func (*Event) Any

func (e *Event) Any(key string, i interface{}) *Event

Any is a wrapper around Event.Interface.

func (*Event) Array

func (e *Event) Array(key string, arr LogArrayMarshaler) *Event

Array adds the field key with an array to the event context. Use e.CreateArray() to create the array or pass a type that implement the LogArrayMarshaler interface.

func (*Event) Bool

func (e *Event) Bool(key string, b bool) *Event

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

func (*Event) Bools

func (e *Event) Bools(key string, b []bool) *Event

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

func (*Event) Bytes

func (e *Event) Bytes(key string, val []byte) *Event

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 (*Event) Caller

func (e *Event) Caller(skip ...int) *Event

Caller adds the file:line of the caller with the zero.CallerFieldName key. The argument skip is the number of stack frames to ascend Skip If not passed, use the global variable CallerSkipFrameCount

func (*Event) CallerSkipFrame

func (e *Event) CallerSkipFrame(skip int) *Event

CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. This includes those added via hooks from the context.

func (*Event) CreateArray

func (e *Event) CreateArray() *Array

CreateArray creates an Array to be used with the *Event.Array method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the *Event.Array method.

func (*Event) CreateDict

func (e *Event) CreateDict() *Event

CreateDict creates an Event to be used with the *Event.Dict method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.

func (*Event) Ctx

func (e *Event) Ctx(ctx context.Context) *Event

Ctx adds the Go Context to the *Event context. The context is not rendered in the output message, but is available to hooks and to Func() calls via the GetCtx() accessor. A typical use case is to extract tracing information from the Go Ctx.

func (*Event) Dict

func (e *Event) Dict(key string, dict *Event) *Event

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

func (*Event) Discard

func (e *Event) Discard() *Event

Discard disables the event so Msg(f) won't print it.

func (*Event) Dur

func (e *Event) Dur(key string, d time.Duration) *Event

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

func (*Event) Durs

func (e *Event) Durs(key string, d []time.Duration) *Event

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

func (*Event) EmbedObject

func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event

EmbedObject marshals an object that implement the LogObjectMarshaler interface.

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

func (e *Event) Err(err error) *Event

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

To customize the key name, change zero.ErrorFieldName.

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

func (*Event) Errs

func (e *Event) Errs(key string, errs []error) *Event

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

func (*Event) Fields

func (e *Event) Fields(fields interface{}) *Event

Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.

func (*Event) Float32

func (e *Event) Float32(key string, f float32) *Event

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

func (*Event) Float64

func (e *Event) Float64(key string, f float64) *Event

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

func (*Event) Floats32

func (e *Event) Floats32(key string, f []float32) *Event

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

func (*Event) Floats64

func (e *Event) Floats64(key string, f []float64) *Event

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

func (*Event) Func

func (e *Event) Func(f func(e *Event)) *Event

Func allows an anonymous func to run only if the event is enabled.

func (*Event) GetCtx

func (e *Event) GetCtx() context.Context

GetCtx retrieves the Go context.Context which is optionally stored in the Event. This allows Hooks and functions passed to Func() to retrieve values which are stored in the context.Context. This can be useful in tracing, where span information is commonly propagated in the context.Context.

func (*Event) Hex

func (e *Event) Hex(key string, val []byte) *Event

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

func (*Event) IPAddr

func (e *Event) IPAddr(key string, ip net.IP) *Event

IPAddr adds the field key with ip as a net.IP IPv4 or IPv6 Address to the event

func (*Event) IPAddrs

func (e *Event) IPAddrs(key string, ip []net.IP) *Event

IPAddrs adds the field key with ip as a net.IP array of IPv4 or IPv6 Address to the event

func (*Event) IPPrefix

func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event

IPPrefix adds the field key with pfx as a net.IPNet IPv4 or IPv6 Prefix (address and mask) to the event

func (*Event) IPPrefixes

func (e *Event) IPPrefixes(key string, pfx []net.IPNet) *Event

IPPrefixes the field key with pfx as a net.IPNet array of IPv4 or IPv6 Prefixes (address and mask) to the event

func (*Event) Int

func (e *Event) Int(key string, i int) *Event

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

func (*Event) Int8

func (e *Event) Int8(key string, i int8) *Event

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

func (*Event) Int16

func (e *Event) Int16(key string, i int16) *Event

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

func (*Event) Int32

func (e *Event) Int32(key string, i int32) *Event

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

func (*Event) Int64

func (e *Event) Int64(key string, i int64) *Event

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

func (*Event) Interface

func (e *Event) Interface(key string, i interface{}) *Event

Interface adds the field key with i marshaled using reflection.

func (*Event) Ints

func (e *Event) Ints(key string, i []int) *Event

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

func (*Event) Ints8

func (e *Event) Ints8(key string, i []int8) *Event

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

func (*Event) Ints16

func (e *Event) Ints16(key string, i []int16) *Event

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

func (*Event) Ints32

func (e *Event) Ints32(key string, i []int32) *Event

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

func (*Event) Ints64

func (e *Event) Ints64(key string, i []int64) *Event

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

func (*Event) MACAddr

func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event

MACAddr the field key with ha as a net.HardwareAddr MAC address to the event

func (*Event) Msg

func (e *Event) Msg(msg string)

Msg sends the *Event with msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msg twice can have unexpected result.

func (*Event) MsgFunc

func (e *Event) MsgFunc(createMsg func() string)

func (*Event) Msgf

func (e *Event) Msgf(format string, v ...interface{})

Msgf sends the event with formatted msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msgf twice can have unexpected result.

func (*Event) Object

func (e *Event) Object(key string, obj LogObjectMarshaler) *Event

Object marshals an object that implement the LogObjectMarshaler interface.

func (*Event) Objects

func (e *Event) Objects(key string, objs []LogObjectMarshaler) *Event

Objects adds the field key with objs as an array of objects that implement the LogObjectMarshaler interface to the event.

This is the array version that accepts a slice of LogObjectMarshaler objects.

func (*Event) ObjectsV

func (e *Event) ObjectsV(key string, objs ...LogObjectMarshaler) *Event

ObjectsV adds the field key with objs as an array of objects that implement the LogObjectMarshaler interface to the event.

This is a variadic version that accepts a list of individual LogObjectMarshaler objects.

func (*Event) RawCBOR

func (e *Event) RawCBOR(key string, b []byte) *Event

RawCBOR adds already encoded CBOR to the log line under key.

No sanity check is performed on b Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url

func (*Event) RawJSON

func (e *Event) RawJSON(key string, b []byte) *Event

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 (*Event) Send

func (e *Event) Send()

Send is equivalent to calling Msg("").

NOTICE: once this method is called, the *Event should be disposed.

func (*Event) Stack

func (e *Event) Stack() *Event

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

ErrorStackMarshaler must be set for this method to do something.

func (*Event) Str

func (e *Event) Str(key, val string) *Event

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

func (*Event) Stringer

func (e *Event) Stringer(key string, val fmt.Stringer) *Event

Stringer adds the field key and a val to the *Event context. If val is not nil, it is added by calling val.String(). If val is nil, it is encoded as null without calling String().

func (*Event) Stringers

func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event

Stringers adds the field key with vals to the *Event context. If a val is not nil, it is added by calling val.String(). If a val is nil, it is encoded as null without calling String().

This is the array version that accepts a slice of fmt.Stringer values.

func (*Event) StringersV

func (e *Event) StringersV(key string, vals ...fmt.Stringer) *Event

StringersV adds the field key with vals to the *Event context. If a val is not nil, it is added by calling val.String(). If a val is nil, it is encoded as null without calling String().

This is a variadic version that accepts a list of individual fmt.Stringer values.

func (*Event) Strs

func (e *Event) Strs(key string, vals []string) *Event

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

This is the array version that accepts a slice of string values.

func (*Event) StrsV

func (e *Event) StrsV(key string, vals ...string) *Event

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

This is a variadic version that accepts a list of individual strings.

func (*Event) Time

func (e *Event) Time(key string, t time.Time) *Event

Time adds the field key with t formatted as string using zero.TimeFieldFormat.

func (*Event) TimeDiff

func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event

TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().

func (*Event) Times

func (e *Event) Times(key string, t []time.Time) *Event

Times adds the field key with t formatted as string using zero.TimeFieldFormat.

func (*Event) Timestamp

func (e *Event) Timestamp() *Event

Timestamp adds the current local time as UNIX timestamp to the *Event context with the TimestampFieldName key. To customize the key name, change zero.TimestampFieldName.

NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one already.

func (*Event) Type

func (e *Event) Type(key string, val interface{}) *Event

Type adds the field key with val's type using reflection.

func (*Event) Uint

func (e *Event) Uint(key string, i uint) *Event

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

func (*Event) Uint8

func (e *Event) Uint8(key string, i uint8) *Event

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

func (*Event) Uint16

func (e *Event) Uint16(key string, i uint16) *Event

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

func (*Event) Uint32

func (e *Event) Uint32(key string, i uint32) *Event

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

func (*Event) Uint64

func (e *Event) Uint64(key string, i uint64) *Event

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

func (*Event) Uints

func (e *Event) Uints(key string, i []uint) *Event

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

func (*Event) Uints8

func (e *Event) Uints8(key string, i []uint8) *Event

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

func (*Event) Uints16

func (e *Event) Uints16(key string, i []uint16) *Event

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

func (*Event) Uints32

func (e *Event) Uints32(key string, i []uint32) *Event

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

func (*Event) Uints64

func (e *Event) Uints64(key string, i []uint64) *Event

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

type FileWriter

type FileWriter struct {
	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.  It uses <processname>-logfile.log in
	// os.TempDir() if empty.
	Filename string `json:"filename" yaml:"filename"`

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int `json:"maxsize" yaml:"maxsize"`

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int `json:"maxage" yaml:"maxage"`

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool `json:"localtime" yaml:"localtime"`

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"`
	// contains filtered or unexported fields
}

FileWriter is an io.WriteCloser that writes to the specified filename.

FileWriter opens or creates the logfile on first Write. If the file exists and is less than MaxSize megabytes, logfile will open and append to that file. If the file exists and its size is >= MaxSize megabytes, the file is renamed by putting the current time in a timestamp in the name immediately before the file's extension (or the end of the filename if there's no extension). A new log file is then created using original filename.

Whenever a write would cause the current log file exceed MaxSize megabytes, the current file is closed, renamed, and a new log file created with the original name. Thus, the filename you give FileWriter is always the "current" log file.

Backups use the log file name given to FileWriter, in the form `name-timestamp.ext` where name is the filename without the extension, timestamp is the time at which the log was rotated formatted with the time.Time format of `2006-01-02T15-04-05.000` and the extension is the original extension. For example, if your FileWriter.Filename is `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log`

Cleaning Up Old Log Files

Whenever a new logfile gets created, old log files may be deleted. The most recent files according to the encoded timestamp will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to.

If MaxBackups and MaxAge are both 0, no old log files will be deleted.

func (*FileWriter) Close

func (l *FileWriter) Close() error

Close implements io.Closer, and closes the current logfile.

func (*FileWriter) Rotate

func (l *FileWriter) Rotate() error

Rotate causes FileWriter to close the existing log file and immediately create a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to SIGHUP. After rotating, this initiates compression and removal of old log files according to the configuration.

func (*FileWriter) Write

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

Write implements io.Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, renamed to include a timestamp of the current time, and a new log file is created using the original log file name. If the length of the write is greater than MaxSize, an error is returned.

type FilteredLevelWriter

type FilteredLevelWriter struct {
	Writer LevelWriter
	Level  Level
}

FilteredLevelWriter writes only logs at Level or above to Writer.

It should be used only in combination with MultiLevelWriter when you want to write to multiple destinations at different levels. Otherwise you should just set the level on the logger and filter events early. When using MultiLevelWriter then you set the level on the logger to the lowest of the levels you use for writers.

func (*FilteredLevelWriter) Close

func (w *FilteredLevelWriter) Close() error

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

func (*FilteredLevelWriter) Write

func (w *FilteredLevelWriter) Write(p []byte) (int, error)

Write writes to the underlying Writer.

func (*FilteredLevelWriter) WriteLevel

func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error)

WriteLevel calls WriteLevel of the underlying Writer only if the level is equal or above the Level.

type Formatter

type Formatter func(interface{}) string

Formatter transforms the input into a formatted string.

type FormatterByFieldName

type FormatterByFieldName func(interface{}, string) string

FormatterByFieldName transforms the input into a formatted string, being able to differentiate formatting based on field name.

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 int8

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

	// TraceLevel defines trace log level.
	TraceLevel Level = -1
)

func GlobalLevel

func GlobalLevel() Level

GlobalLevel returns the current global log level

func ParseLevel

func ParseLevel(levelStr string) (Level, error)

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

func (Level) MarshalText

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

MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats

func (Level) String

func (l Level) String() string

func (*Level) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats

type LevelHook

type LevelHook struct {
	NoLevelHook, TraceHook, 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 LevelSampler

type LevelSampler struct {
	TraceSampler, DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler
}

LevelSampler applies a different sampler for each level.

func (LevelSampler) Sample

func (s LevelSampler) Sample(lvl Level) bool

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.

func SyslogCEEWriter

func SyslogCEEWriter(w SyslogWriter) LevelWriter

SyslogCEEWriter wraps a SyslogWriter with a SyslogLevelWriter that adds a MITRE CEE prefix for JSON syslog entries, compatible with rsyslog and syslog-ng JSON logging support. See https://www.rsyslog.com/json-elasticsearch/

func SyslogLevelWriter

func SyslogLevelWriter(w SyslogWriter) LevelWriter

SyslogLevelWriter wraps a SyslogWriter and call the right syslog level method matching the zero level.

type LevelWriterAdapter

type LevelWriterAdapter struct {
	io.Writer
}

LevelWriterAdapter adapts an io.Writer to support the LevelWriter interface.

func (LevelWriterAdapter) Close

func (lw LevelWriterAdapter) Close() error

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

func (LevelWriterAdapter) WriteLevel

func (lw LevelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error)

WriteLevel simply writes everything to the adapted writer, ignoring the level.

type LogArrayMarshaler

type LogArrayMarshaler interface {
	MarshalZeroArray(a *Array)
}

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

type LogObjectMarshaler

type LogObjectMarshaler interface {
	MarshalZeroObject(e *Event)
}

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

func AsLogObjectMarshalers

func AsLogObjectMarshalers[T LogObjectMarshaler](objs []T) []LogObjectMarshaler

AsLogObjectMarshalers converts a slice of T (implementing LogObjectMarshaler) into a slice of LogObjectMarshaler.

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 guarantee on access serialization to the Writer. If your Writer is not thread safe, you may consider a sync wrapper.

func Ctx

func Ctx(ctx context.Context) *Logger

Ctx returns the Logger associated with the ctx. If no logger is associated, DefaultContextLogger is returned, unless DefaultContextLogger is nil, in which case a disabled logger is returned.

func New

func New(w io.Writer) Logger

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

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

func Nop

func Nop() Logger

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

func (*Logger) Debug

func (l *Logger) Debug() *Event

Debug starts a new message with debug level.

You must call Msg on the returned event in order to send the event.

func (Logger) Encoder

func (l Logger) Encoder(e Encoder) Logger

Encoder returns a logger with the e log message encoder (JSON, CBOR, ...). By default, loggers use the JSON encoder; use NewCBOREncoder to produce binary logs or provide your own Encoder implementation for other formats.

func (*Logger) Err

func (l *Logger) Err(err error) *Event

Err starts a new message with error level with err as a field if not nil or with info level if err is nil.

You must call Msg on the returned event in order to send the event.

func (*Logger) Error

func (l *Logger) Error() *Event

Error starts a new message with error level.

You must call Msg on the returned event in order to send the event.

func (*Logger) Fatal

func (l *Logger) Fatal() *Event

Fatal starts a new message with fatal level. The FatalExitFunc interceptor function is called by the Msg method, which by default terminates the program immediately using os.Exit(1), any desired behavior can be implemented by setting FatalExitFunc.

You must call Msg on the returned event in order to send the event.

func (Logger) GetLevel

func (l Logger) GetLevel() Level

GetLevel returns the current Level of l.

func (Logger) Hook

func (l Logger) Hook(hooks ...Hook) Logger

Hook returns a logger with the h Hook.

func (*Logger) Info

func (l *Logger) Info() *Event

Info starts a new message with info level.

You must call Msg on the returned event in order to send the event.

func (Logger) Level

func (l Logger) Level(lvl Level) Logger

Level creates a child logger with the minimum accepted level set to level.

func (*Logger) Log

func (l *Logger) Log() *Event

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

You must call Msg on the returned event in order to send the event.

func (Logger) Output

func (l Logger) Output(w io.Writer) Logger

Output duplicates the current logger and sets w as its output.

func (*Logger) Panic

func (l *Logger) Panic() *Event

Panic starts a new message with panic level. The panic() function is called by the Msg method, which stops the ordinary flow of a goroutine.

You must call Msg on the returned event in order to send the event.

func (*Logger) Print

func (l *Logger) Print(v ...interface{})

Print sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Print.

func (*Logger) Printf

func (l *Logger) Printf(format string, v ...interface{})

Printf sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Println

func (l *Logger) Println(v ...interface{})

Println sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Println.

func (Logger) Sample

func (l Logger) Sample(s Sampler) Logger

Sample returns a logger with the s sampler.

func (*Logger) Trace

func (l *Logger) Trace() *Event

Trace starts a new message with trace level.

You must call Msg on the returned event in order to send the event.

func (*Logger) UpdateContext

func (l *Logger) UpdateContext(update func(c Context) Context)

UpdateContext updates the internal logger's context.

Caution: This method is not concurrency safe. Use the With method to create a child logger before modifying the context from concurrent goroutines.

func (*Logger) Warn

func (l *Logger) Warn() *Event

Warn starts a new message with warn level.

You must call Msg on the returned event in order to send the event.

func (Logger) With

func (l Logger) With() Context

With creates a child logger with the field added to its context.

func (Logger) WithContext

func (l Logger) WithContext(ctx context.Context) context.Context

WithContext returns a copy of ctx with the receiver attached. The Logger attached to the provided Context (if any) will not be affected. If the receiver's log level is Disabled it will only be attached to the returned Context if the provided Context has a previously attached Logger. If the provided Context has no attached Logger, a Disabled Logger will not be attached.

Note: to modify the existing Logger attached to a Context (instead of replacing it in a new Context), use UpdateContext with the following notation:

ctx := r.Context()
l := zero.Ctx(ctx)
l.UpdateContext(func(c Context) Context {
    return c.Str("bar", "baz")
})

func (*Logger) WithLevel

func (l *Logger) WithLevel(level Level) *Event

WithLevel starts a new message with level. Unlike Fatal and Panic methods, WithLevel does not terminate the program or stop the ordinary flow of a goroutine when used with their respective levels.

You must call Msg on the returned event in order to send the event.

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.

type RandomSampler

type RandomSampler uint32

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

func (RandomSampler) Sample

func (s RandomSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

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 SlogHandler

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

SlogHandler implements the slog.Handler interface using a zero.Logger as the underlying log backend. This allows code that uses the standard library's slog package to route log output through zero.

func NewSlogHandler

func NewSlogHandler(logger Logger) *SlogHandler

NewSlogHandler creates a new slog.Handler that writes log records to the given zero.Logger. The handler maps slog levels to zero levels and converts slog attributes to zero fields.

func (*SlogHandler) Enabled

func (h *SlogHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level. It mirrors Logger.should's level and writer checks (without sampling).

func (*SlogHandler) Handle

func (h *SlogHandler) Handle(ctx context.Context, record slog.Record) error

Handle handles the Record. It converts the slog.Record into a zero event and writes it using the underlying zero.Logger.

func (*SlogHandler) WithAttrs

func (h *SlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler with the given attributes pre-attached. These attributes will be included in every subsequent log record.

func (*SlogHandler) WithGroup

func (h *SlogHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group name. All subsequent attributes will be nested under this group name in the output.

type SyslogWriter

type SyslogWriter interface {
	io.Writer
	Debug(m string) error
	Info(m string) error
	Warning(m string) error
	Err(m string) error
	Emerg(m string) error
	Crit(m string) error
}

SyslogWriter is an interface matching a syslog.Writer struct.

type TerminalWriter

type TerminalWriter struct {
	// Out is the output destination.
	Out io.Writer

	// NoColor disables the colorized output.
	NoColor bool

	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string

	// TimeLocation tells TerminalWriter’s default FormatTimestamp
	// how to localize the time.
	TimeLocation *time.Location

	// PartsOrder defines the order of parts in output.
	PartsOrder []string

	// PartsExclude defines parts to not display in output.
	PartsExclude []string

	// FieldsOrder defines the order of contextual fields in output.
	FieldsOrder []string

	// FieldsExclude defines contextual fields to not display in output.
	FieldsExclude []string

	FormatTimestamp     Formatter
	FormatLevel         Formatter
	FormatCaller        Formatter
	FormatMessage       Formatter
	FormatFieldName     Formatter
	FormatFieldValue    Formatter
	FormatErrFieldName  Formatter
	FormatErrFieldValue Formatter
	// If this is configured it is used for "part" values and
	// has precedence on FormatFieldValue
	FormatPartValueByName FormatterByFieldName

	FormatExtra func(map[string]interface{}, *bytes.Buffer) error

	FormatPrepare func(map[string]interface{}) error
	// contains filtered or unexported fields
}

TerminalWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Out.

func NewTerminalWriter

func NewTerminalWriter(options ...func(w *TerminalWriter)) TerminalWriter

NewTerminalWriter creates and initializes a new TerminalWriter.

func (TerminalWriter) Close

func (w TerminalWriter) Close() error

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

func (TerminalWriter) Write

func (w TerminalWriter) Write(p []byte) (n int, err error)

Write transforms the JSON input with formatters and appends to w.Out.

type TestWriter

type TestWriter struct {
	T TestingLog

	// Frame skips caller frames to capture the original file and line numbers.
	Frame int
}

TestWriter is a writer that writes to testing.TB.

func NewTestWriter

func NewTestWriter(t TestingLog) TestWriter

NewTestWriter creates a writer that logs to the testing.TB.

func (TestWriter) Write

func (t TestWriter) Write(p []byte) (n int, err error)

Write to testing.TB.

type TestingLog

type TestingLog interface {
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	Helper()
}

TestingLog is the logging interface of testing.TB.

type TriggerLevelWriter

type TriggerLevelWriter struct {
	// Destination writer. If LevelWriter is provided (usually), its WriteLevel is used
	// instead of Write.
	io.Writer

	// ConditionalLevel is the level (and below) at which lines are buffered until
	// a trigger level (or higher) line is emitted. Usually this is set to DebugLevel.
	ConditionalLevel Level

	// TriggerLevel is the lowest level that triggers the sending of the conditional
	// level lines. Usually this is set to ErrorLevel.
	TriggerLevel Level
	// contains filtered or unexported fields
}

TriggerLevelWriter buffers log lines at the ConditionalLevel or below until a trigger level (or higher) line is emitted. Log lines with level higher than ConditionalLevel are always written out to the destination writer. If trigger never happens, buffered log lines are never written out.

It can be used to configure "log level per request".

func (*TriggerLevelWriter) Close

func (w *TriggerLevelWriter) Close() error

Close closes the writer and returns the buffer to the pool.

func (*TriggerLevelWriter) Trigger

func (w *TriggerLevelWriter) Trigger() error

Trigger forces flushing the buffer and change the trigger state to triggered, if the writer has not already been triggered before.

func (*TriggerLevelWriter) WriteLevel

func (w *TriggerLevelWriter) WriteLevel(l Level, p []byte) (n int, err error)

Directories

Path Synopsis
cbor
Package cbor provides primitives for storing different data in the CBOR (binary) format.
Package cbor provides primitives for storing different data in the CBOR (binary) format.
Package log provides a global logger for zero.
Package log provides a global logger for zero.

Jump to

Keyboard shortcuts

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